Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 49 additions & 36 deletions lightning/src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -6314,6 +6314,19 @@ where
}
}

#[cfg(all(test))]
pub fn get_initial_counterparty_commitment_signatures_for_test<L: Deref>(
&mut self, funding: &mut FundingScope, logger: &L,
counterparty_next_commitment_point_override: PublicKey,
) -> Option<(Signature, Vec<Signature>)>
where
SP::Target: SignerProvider,
L::Target: Logger,
{
self.counterparty_next_commitment_point = Some(counterparty_next_commitment_point_override);
self.get_initial_counterparty_commitment_signatures(funding, logger)
}

fn check_funding_meets_minimum_depth(&self, funding: &FundingScope, height: u32) -> bool {
let minimum_depth = self
.minimum_depth(funding)
Expand DownExpand Up@@ -13946,7 +13959,9 @@ where
pub funding: FundingScope,
pub context: ChannelContext<SP>,
pub unfunded_context: UnfundedChannelContext,
pub funding_negotiation_context: FundingNegotiationContext,
funding_tx_locktime: LockTime,
#[allow(unused)] // TODO(dual_funding): Remove once initiating V2 channels is enabled.
pub funding_negotiation_context: Option<FundingNegotiationContext>,
/// The current interactive transaction construction session under negotiation.
pub interactive_tx_constructor: Option<InteractiveTxConstructor>,
}
Expand DownExpand Up@@ -14021,7 +14036,8 @@ where
funding,
context,
unfunded_context,
funding_negotiation_context,
funding_tx_locktime,
funding_negotiation_context: Some(funding_negotiation_context),
interactive_tx_constructor: None,
};
Ok(chan)
Expand DownExpand Up@@ -14096,29 +14112,28 @@ where
},
funding_feerate_sat_per_1000_weight: self.context.feerate_per_kw,
second_per_commitment_point,
locktime: self.funding_negotiation_context.funding_tx_locktime.to_consensus_u32(),
locktime: self.funding_tx_locktime.to_consensus_u32(),
require_confirmed_inputs: None,
}
}

/// Creates a new dual-funded channel from a remote side's request for one.
/// Assumes chain_hash has already been checked and corresponds with what we expect!
/// TODO(dual_funding): Allow contributions, pass intended amount and inputs
#[allow(dead_code)] // TODO(dual_funding): Remove once V2 channels is enabled.
#[rustfmt::skip]
pub fn new_inbound<ES: Deref, F: Deref, L: Deref>(
fee_estimator: &LowerBoundedFeeEstimator<F>, entropy_source: &ES, signer_provider: &SP,
holder_node_id: PublicKey, counterparty_node_id: PublicKey, our_supported_features: &ChannelTypeFeatures,
their_features: &InitFeatures, msg: &msgs::OpenChannelV2,
user_id: u128, config: &UserConfig, current_chain_height: u32, logger: &L,
their_features: &InitFeatures, msg: &msgs::OpenChannelV2, user_id: u128, config: &UserConfig,
current_chain_height: u32, logger: &L, our_funding_contribution: Amount,
our_funding_inputs: Vec<FundingTxInput>, change_script: Option<ScriptBuf>,
) -> Result<Self, ChannelError>
where ES::Target: EntropySource,
F::Target: FeeEstimator,
L::Target: Logger,
{
// TODO(dual_funding): Take these as input once supported
let (our_funding_contribution, our_funding_contribution_sats) = (SignedAmount::ZERO, 0u64);
let our_funding_inputs = Vec::new();
debug_assert!(our_funding_contribution <= Amount::MAX_MONEY);
let our_funding_contribution_sats = our_funding_contribution.to_sat();

let channel_value_satoshis =
our_funding_contribution_sats.saturating_add(msg.common_fields.funding_satoshis);
Expand DownExpand Up@@ -14161,39 +14176,33 @@ where
&funding.get_counterparty_pubkeys().revocation_basepoint);
context.channel_id = channel_id;

let funding_tx_locktime = LockTime::from_consensus(msg.locktime);
let funding_negotiation_context = FundingNegotiationContext {
is_initiator: false,
our_funding_contribution,
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
our_funding_contribution: our_funding_contribution
.to_signed()
.expect("our_funding_contribution should not be greater than Amount::MAX_MONEY"),
funding_tx_locktime,
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
shared_funding_input: None,
our_funding_inputs: our_funding_inputs.clone(),
our_funding_outputs: Vec::new(),
change_script: None,
};
let shared_funding_output = TxOut {
value: Amount::from_sat(funding.get_value_satoshis()),
script_pubkey: funding.get_funding_redeemscript().to_p2wsh(),
change_script,
};

let interactive_tx_constructor = Some(InteractiveTxConstructor::new(
InteractiveTxConstructorArgs {
let mut interactive_tx_constructor = funding_negotiation_context
.into_interactive_tx_constructor(
&context,
&funding,
signer_provider,
entropy_source,
holder_node_id,
counterparty_node_id,
channel_id: context.channel_id,
feerate_sat_per_kw: funding_negotiation_context.funding_feerate_sat_per_1000_weight,
funding_tx_locktime: funding_negotiation_context.funding_tx_locktime,
is_initiator: false,
inputs_to_contribute: our_funding_inputs,
shared_funding_input: None,
shared_funding_output: SharedOwnedOutput::new(shared_funding_output, our_funding_contribution_sats),
outputs_to_contribute: funding_negotiation_context.our_funding_outputs.clone(),
}
).map_err(|err| {
let reason = ClosureReason::ProcessingError { err: err.reason.to_string() };
ChannelError::Close((err.reason.to_string(), reason))
})?);
)
.map_err(|err| {
let reason = ClosureReason::ProcessingError { err: err.reason.to_string() };
ChannelError::Close((err.reason.to_string(), reason))
})?;
debug_assert!(interactive_tx_constructor.take_initiator_first_message().is_none());

let unfunded_context = UnfundedChannelContext {
unfunded_channel_age_ticks: 0,
Expand All@@ -14202,9 +14211,10 @@ where
Ok(Self {
funding,
context,
funding_negotiation_context,
interactive_tx_constructor,
unfunded_context,
funding_tx_locktime,
funding_negotiation_context: None,
interactive_tx_constructor: Some(interactive_tx_constructor),
Comment on lines +14216 to +14217

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would be nice to reuse FundingNegotiation here, but it seems unclear whether the last AwaitingSignatures state can be adapted to the initial dual funding state

})
}

Expand DownExpand Up@@ -14267,8 +14277,7 @@ where
}),
channel_type: Some(self.funding.get_channel_type().clone()),
},
funding_satoshis: self.funding_negotiation_context.our_funding_contribution.to_sat()
as u64,
funding_satoshis: self.our_funding_contribution().to_sat(),
second_per_commitment_point,
require_confirmed_inputs: None,
}
Expand All@@ -14283,6 +14292,10 @@ where
pub fn get_accept_channel_v2_message(&self) -> msgs::AcceptChannelV2 {
self.generate_accept_channel_v2_message()
}

pub fn our_funding_contribution(&self) -> Amount {
Amount::from_sat(self.funding.value_to_self_msat / 1000)
}
}

// Unfunded channel utilities
Expand Down
77 changes: 69 additions & 8 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -30,7 +30,7 @@ use bitcoin::hashes::{Hash, HashEngine, HmacEngine};

use bitcoin::secp256k1::Secp256k1;
use bitcoin::secp256k1::{PublicKey, SecretKey};
use bitcoin::{secp256k1, Sequence, SignedAmount};
use bitcoin::{secp256k1, Amount, ScriptBuf, Sequence};

use crate::blinded_path::message::{
AsyncPaymentsContext, BlindedMessagePath, MessageForwardNode, OffersContext,
Expand DownExpand Up@@ -65,7 +65,7 @@ use crate::ln::channel::{
WithChannelContext,
};
use crate::ln::channel_state::ChannelDetails;
use crate::ln::funding::SpliceContribution;
use crate::ln::funding::{FundingTxInput, SpliceContribution};
use crate::ln::inbound_payment;
use crate::ln::interactivetxs::InteractiveTxMessageSend;
use crate::ln::msgs;
Expand DownExpand Up@@ -9814,6 +9814,9 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
false,
user_channel_id,
config_overrides,
Amount::ZERO,
vec![],
None,
)
}

Expand DownExpand Up@@ -9845,15 +9848,73 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
true,
user_channel_id,
config_overrides,
Amount::ZERO,
vec![],
None,
)
}

/// Accepts a request to open a dual-funded channel with a contribution provided after an
/// [`Event::OpenChannelRequest`].
///
/// The [`Event::OpenChannelRequest::channel_negotiation_type`] field will indicate the open channel
/// request is for a dual-funded channel when the variant is [`InboundChannelFunds::DualFunded`].
///
/// The `temporary_channel_id` parameter indicates which inbound channel should be accepted,
/// and the `counterparty_node_id` parameter is the id of the peer that 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_channel_*` call.
///
/// The `funding_inputs` parameter provides which UTXOs to use for `our_funding_contribution`
/// along with the corresponding satisfaction weight. They must be able to cover any fees needed
/// to pay for the contributed weight to the funding transaction. This includes the witnesses
/// provided through calling [`ChannelManager::funding_transaction_signed`] after receiving
/// [`Event::FundingTransactionReadyForSigning`].
///
/// 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://diyhpl.us/~bryan/irc/bitcoin/bitcoin-dev/linuxfoundation-pipermail/lightning-dev/2023-May/003922.txt
///
/// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
/// [`Event::OpenChannelRequest::channel_negotiation_type`]: events::Event::OpenChannelRequest::channel_negotiation_type
/// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
/// [`Event::FundingTransactionReadyForSigning`]: events::Event::FundingTransactionReadyForSigning
/// [`ChannelManager::funding_transaction_signed`]: ChannelManager::funding_transaction_signed
pub fn accept_inbound_channel_with_contribution(
&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey,
user_channel_id: u128, config_overrides: Option<ChannelConfigOverrides>,
our_funding_contribution: Amount, funding_inputs: Vec<FundingTxInput>,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're also allowed to include outputs, behaving similar to the mixed mode splice, so maybe it's worth waiting until we figure that out in #4261 so we can adopt it here?

change_script: Option<ScriptBuf>,
) -> Result<(), APIError> {
self.do_accept_inbound_channel(
temporary_channel_id,
counterparty_node_id,
false,
user_channel_id,
config_overrides,
our_funding_contribution,
funding_inputs,
change_script,
)
}

/// TODO(dual_funding): Allow contributions, pass intended amount and inputs
#[rustfmt::skip]
fn do_accept_inbound_channel(
&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, accept_0conf: bool,
user_channel_id: u128, config_overrides: Option<ChannelConfigOverrides>
&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey,
accept_0conf: bool, user_channel_id: u128, config_overrides: Option<ChannelConfigOverrides>,
our_funding_contribution: Amount, funding_inputs: Vec<FundingTxInput>,
change_script: Option<ScriptBuf>,
) -> Result<(), APIError> {
if our_funding_contribution > Amount::MAX_MONEY {
return Err(APIError::APIMisuseError {
err: format!("the funding contribution must be smaller than the total bitcoin supply, it was {}", our_funding_contribution)
});
}

let mut config = self.config.read().unwrap().clone();

Expand DownExpand Up@@ -9911,7 +9972,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
&self.channel_type_features(), &peer_state.latest_features,
&open_channel_msg,
user_channel_id, &config, best_block_height,
&self.logger,
&self.logger, our_funding_contribution, funding_inputs, change_script,
).map_err(|e| {
let channel_id = open_channel_msg.common_fields.temporary_channel_id;
MsgHandleErrInternal::from_chan_no_close(e, channel_id)
Expand DownExpand Up@@ -10055,7 +10116,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/

// Inbound V2 channels with contributed inputs are not considered unfunded.
if let Some(unfunded_chan) = chan.as_unfunded_v2() {
if unfunded_chan.funding_negotiation_context.our_funding_contribution > SignedAmount::ZERO {
if unfunded_chan.our_funding_contribution() > Amount::ZERO {
continue;
}
}
Expand DownExpand Up@@ -10197,7 +10258,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
&self.fee_estimator, &self.entropy_source, &self.signer_provider,
self.get_our_node_id(), *counterparty_node_id, &self.channel_type_features(),
&peer_state.latest_features, msg, user_channel_id,
&self.config.read().unwrap(), best_block_height, &self.logger,
&self.config.read().unwrap(), best_block_height, &self.logger, Amount::ZERO, vec![], None,
).map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.common_fields.temporary_channel_id))?;
let message_send_event = MessageSendEvent::SendAcceptChannelV2 {
node_id: *counterparty_node_id,
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 49 additions & 36 deletions lightning/src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -6314,6 +6314,19 @@ where
}
}

#[cfg(all(test))]
pub fn get_initial_counterparty_commitment_signatures_for_test<L: Deref>(
&mut self, funding: &mut FundingScope, logger: &L,
counterparty_next_commitment_point_override: PublicKey,
) -> Option<(Signature, Vec<Signature>)>
where
SP::Target: SignerProvider,
L::Target: Logger,
{
self.counterparty_next_commitment_point = Some(counterparty_next_commitment_point_override);
self.get_initial_counterparty_commitment_signatures(funding, logger)
}

fn check_funding_meets_minimum_depth(&self, funding: &FundingScope, height: u32) -> bool {
let minimum_depth = self
.minimum_depth(funding)
Expand DownExpand Up@@ -13946,7 +13959,9 @@ where
pub funding: FundingScope,
pub context: ChannelContext<SP>,
pub unfunded_context: UnfundedChannelContext,
pub funding_negotiation_context: FundingNegotiationContext,
funding_tx_locktime: LockTime,
#[allow(unused)] // TODO(dual_funding): Remove once initiating V2 channels is enabled.
pub funding_negotiation_context: Option<FundingNegotiationContext>,
/// The current interactive transaction construction session under negotiation.
pub interactive_tx_constructor: Option<InteractiveTxConstructor>,
}
Expand DownExpand Up@@ -14021,7 +14036,8 @@ where
funding,
context,
unfunded_context,
funding_negotiation_context,
funding_tx_locktime,
funding_negotiation_context: Some(funding_negotiation_context),
interactive_tx_constructor: None,
};
Ok(chan)
Expand DownExpand Up@@ -14096,29 +14112,28 @@ where
},
funding_feerate_sat_per_1000_weight: self.context.feerate_per_kw,
second_per_commitment_point,
locktime: self.funding_negotiation_context.funding_tx_locktime.to_consensus_u32(),
locktime: self.funding_tx_locktime.to_consensus_u32(),
require_confirmed_inputs: None,
}
}

/// Creates a new dual-funded channel from a remote side's request for one.
/// Assumes chain_hash has already been checked and corresponds with what we expect!
/// TODO(dual_funding): Allow contributions, pass intended amount and inputs
#[allow(dead_code)] // TODO(dual_funding): Remove once V2 channels is enabled.
#[rustfmt::skip]
pub fn new_inbound<ES: Deref, F: Deref, L: Deref>(
fee_estimator: &LowerBoundedFeeEstimator<F>, entropy_source: &ES, signer_provider: &SP,
holder_node_id: PublicKey, counterparty_node_id: PublicKey, our_supported_features: &ChannelTypeFeatures,
their_features: &InitFeatures, msg: &msgs::OpenChannelV2,
user_id: u128, config: &UserConfig, current_chain_height: u32, logger: &L,
their_features: &InitFeatures, msg: &msgs::OpenChannelV2, user_id: u128, config: &UserConfig,
current_chain_height: u32, logger: &L, our_funding_contribution: Amount,
our_funding_inputs: Vec<FundingTxInput>, change_script: Option<ScriptBuf>,
) -> Result<Self, ChannelError>
where ES::Target: EntropySource,
F::Target: FeeEstimator,
L::Target: Logger,
{
// TODO(dual_funding): Take these as input once supported
let (our_funding_contribution, our_funding_contribution_sats) = (SignedAmount::ZERO, 0u64);
let our_funding_inputs = Vec::new();
debug_assert!(our_funding_contribution <= Amount::MAX_MONEY);
let our_funding_contribution_sats = our_funding_contribution.to_sat();

let channel_value_satoshis =
our_funding_contribution_sats.saturating_add(msg.common_fields.funding_satoshis);
Expand DownExpand Up@@ -14161,39 +14176,33 @@ where
&funding.get_counterparty_pubkeys().revocation_basepoint);
context.channel_id = channel_id;

let funding_tx_locktime = LockTime::from_consensus(msg.locktime);
let funding_negotiation_context = FundingNegotiationContext {
is_initiator: false,
our_funding_contribution,
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
our_funding_contribution: our_funding_contribution
.to_signed()
.expect("our_funding_contribution should not be greater than Amount::MAX_MONEY"),
funding_tx_locktime,
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
shared_funding_input: None,
our_funding_inputs: our_funding_inputs.clone(),
our_funding_outputs: Vec::new(),
change_script: None,
};
let shared_funding_output = TxOut {
value: Amount::from_sat(funding.get_value_satoshis()),
script_pubkey: funding.get_funding_redeemscript().to_p2wsh(),
change_script,
};

let interactive_tx_constructor = Some(InteractiveTxConstructor::new(
InteractiveTxConstructorArgs {
let mut interactive_tx_constructor = funding_negotiation_context
.into_interactive_tx_constructor(
&context,
&funding,
signer_provider,
entropy_source,
holder_node_id,
counterparty_node_id,
channel_id: context.channel_id,
feerate_sat_per_kw: funding_negotiation_context.funding_feerate_sat_per_1000_weight,
funding_tx_locktime: funding_negotiation_context.funding_tx_locktime,
is_initiator: false,
inputs_to_contribute: our_funding_inputs,
shared_funding_input: None,
shared_funding_output: SharedOwnedOutput::new(shared_funding_output, our_funding_contribution_sats),
outputs_to_contribute: funding_negotiation_context.our_funding_outputs.clone(),
}
).map_err(|err| {
let reason = ClosureReason::ProcessingError { err: err.reason.to_string() };
ChannelError::Close((err.reason.to_string(), reason))
})?);
)
.map_err(|err| {
let reason = ClosureReason::ProcessingError { err: err.reason.to_string() };
ChannelError::Close((err.reason.to_string(), reason))
})?;
debug_assert!(interactive_tx_constructor.take_initiator_first_message().is_none());

let unfunded_context = UnfundedChannelContext {
unfunded_channel_age_ticks: 0,
Expand All@@ -14202,9 +14211,10 @@ where
Ok(Self {
funding,
context,
funding_negotiation_context,
interactive_tx_constructor,
unfunded_context,
funding_tx_locktime,
funding_negotiation_context: None,
interactive_tx_constructor: Some(interactive_tx_constructor),
Comment on lines +14216 to +14217

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would be nice to reuse FundingNegotiation here, but it seems unclear whether the last AwaitingSignatures state can be adapted to the initial dual funding state

})
}

Expand DownExpand Up@@ -14267,8 +14277,7 @@ where
}),
channel_type: Some(self.funding.get_channel_type().clone()),
},
funding_satoshis: self.funding_negotiation_context.our_funding_contribution.to_sat()
as u64,
funding_satoshis: self.our_funding_contribution().to_sat(),
second_per_commitment_point,
require_confirmed_inputs: None,
}
Expand All@@ -14283,6 +14292,10 @@ where
pub fn get_accept_channel_v2_message(&self) -> msgs::AcceptChannelV2 {
self.generate_accept_channel_v2_message()
}

pub fn our_funding_contribution(&self) -> Amount {
Amount::from_sat(self.funding.value_to_self_msat / 1000)
}
}

// Unfunded channel utilities
Expand Down
77 changes: 69 additions & 8 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -30,7 +30,7 @@ use bitcoin::hashes::{Hash, HashEngine, HmacEngine};

use bitcoin::secp256k1::Secp256k1;
use bitcoin::secp256k1::{PublicKey, SecretKey};
use bitcoin::{secp256k1, Sequence, SignedAmount};
use bitcoin::{secp256k1, Amount, ScriptBuf, Sequence};

use crate::blinded_path::message::{
AsyncPaymentsContext, BlindedMessagePath, MessageForwardNode, OffersContext,
Expand DownExpand Up@@ -65,7 +65,7 @@ use crate::ln::channel::{
WithChannelContext,
};
use crate::ln::channel_state::ChannelDetails;
use crate::ln::funding::SpliceContribution;
use crate::ln::funding::{FundingTxInput, SpliceContribution};
use crate::ln::inbound_payment;
use crate::ln::interactivetxs::InteractiveTxMessageSend;
use crate::ln::msgs;
Expand DownExpand Up@@ -9814,6 +9814,9 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
false,
user_channel_id,
config_overrides,
Amount::ZERO,
vec![],
None,
)
}

Expand DownExpand Up@@ -9845,15 +9848,73 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
true,
user_channel_id,
config_overrides,
Amount::ZERO,
vec![],
None,
)
}

/// Accepts a request to open a dual-funded channel with a contribution provided after an
/// [`Event::OpenChannelRequest`].
///
/// The [`Event::OpenChannelRequest::channel_negotiation_type`] field will indicate the open channel
/// request is for a dual-funded channel when the variant is [`InboundChannelFunds::DualFunded`].
///
/// The `temporary_channel_id` parameter indicates which inbound channel should be accepted,
/// and the `counterparty_node_id` parameter is the id of the peer that 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_channel_*` call.
///
/// The `funding_inputs` parameter provides which UTXOs to use for `our_funding_contribution`
/// along with the corresponding satisfaction weight. They must be able to cover any fees needed
/// to pay for the contributed weight to the funding transaction. This includes the witnesses
/// provided through calling [`ChannelManager::funding_transaction_signed`] after receiving
/// [`Event::FundingTransactionReadyForSigning`].
///
/// 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://diyhpl.us/~bryan/irc/bitcoin/bitcoin-dev/linuxfoundation-pipermail/lightning-dev/2023-May/003922.txt
///
/// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
/// [`Event::OpenChannelRequest::channel_negotiation_type`]: events::Event::OpenChannelRequest::channel_negotiation_type
/// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
/// [`Event::FundingTransactionReadyForSigning`]: events::Event::FundingTransactionReadyForSigning
/// [`ChannelManager::funding_transaction_signed`]: ChannelManager::funding_transaction_signed
pub fn accept_inbound_channel_with_contribution(
&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey,
user_channel_id: u128, config_overrides: Option<ChannelConfigOverrides>,
our_funding_contribution: Amount, funding_inputs: Vec<FundingTxInput>,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're also allowed to include outputs, behaving similar to the mixed mode splice, so maybe it's worth waiting until we figure that out in #4261 so we can adopt it here?

change_script: Option<ScriptBuf>,
) -> Result<(), APIError> {
self.do_accept_inbound_channel(
temporary_channel_id,
counterparty_node_id,
false,
user_channel_id,
config_overrides,
our_funding_contribution,
funding_inputs,
change_script,
)
}

/// TODO(dual_funding): Allow contributions, pass intended amount and inputs
#[rustfmt::skip]
fn do_accept_inbound_channel(
&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, accept_0conf: bool,
user_channel_id: u128, config_overrides: Option<ChannelConfigOverrides>
&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey,
accept_0conf: bool, user_channel_id: u128, config_overrides: Option<ChannelConfigOverrides>,
our_funding_contribution: Amount, funding_inputs: Vec<FundingTxInput>,
change_script: Option<ScriptBuf>,
) -> Result<(), APIError> {
if our_funding_contribution > Amount::MAX_MONEY {
return Err(APIError::APIMisuseError {
err: format!("the funding contribution must be smaller than the total bitcoin supply, it was {}", our_funding_contribution)
});
}

let mut config = self.config.read().unwrap().clone();

Expand DownExpand Up@@ -9911,7 +9972,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
&self.channel_type_features(), &peer_state.latest_features,
&open_channel_msg,
user_channel_id, &config, best_block_height,
&self.logger,
&self.logger, our_funding_contribution, funding_inputs, change_script,
).map_err(|e| {
let channel_id = open_channel_msg.common_fields.temporary_channel_id;
MsgHandleErrInternal::from_chan_no_close(e, channel_id)
Expand DownExpand Up@@ -10055,7 +10116,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/

// Inbound V2 channels with contributed inputs are not considered unfunded.
if let Some(unfunded_chan) = chan.as_unfunded_v2() {
if unfunded_chan.funding_negotiation_context.our_funding_contribution > SignedAmount::ZERO {
if unfunded_chan.our_funding_contribution() > Amount::ZERO {
continue;
}
}
Expand DownExpand Up@@ -10197,7 +10258,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
&self.fee_estimator, &self.entropy_source, &self.signer_provider,
self.get_our_node_id(), *counterparty_node_id, &self.channel_type_features(),
&peer_state.latest_features, msg, user_channel_id,
&self.config.read().unwrap(), best_block_height, &self.logger,
&self.config.read().unwrap(), best_block_height, &self.logger, Amount::ZERO, vec![], None,
).map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.common_fields.temporary_channel_id))?;
let message_send_event = MessageSendEvent::SendAcceptChannelV2 {
node_id: *counterparty_node_id,
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 49 additions & 36 deletions lightning/src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -6314,6 +6314,19 @@ where
}
}

#[cfg(all(test))]
pub fn get_initial_counterparty_commitment_signatures_for_test<L: Deref>(
&mut self, funding: &mut FundingScope, logger: &L,
counterparty_next_commitment_point_override: PublicKey,
) -> Option<(Signature, Vec<Signature>)>
where
SP::Target: SignerProvider,
L::Target: Logger,
{
self.counterparty_next_commitment_point = Some(counterparty_next_commitment_point_override);
self.get_initial_counterparty_commitment_signatures(funding, logger)
}

fn check_funding_meets_minimum_depth(&self, funding: &FundingScope, height: u32) -> bool {
let minimum_depth = self
.minimum_depth(funding)
Expand DownExpand Up@@ -13946,7 +13959,9 @@ where
pub funding: FundingScope,
pub context: ChannelContext<SP>,
pub unfunded_context: UnfundedChannelContext,
pub funding_negotiation_context: FundingNegotiationContext,
funding_tx_locktime: LockTime,
#[allow(unused)] // TODO(dual_funding): Remove once initiating V2 channels is enabled.
pub funding_negotiation_context: Option<FundingNegotiationContext>,
/// The current interactive transaction construction session under negotiation.
pub interactive_tx_constructor: Option<InteractiveTxConstructor>,
}
Expand DownExpand Up@@ -14021,7 +14036,8 @@ where
funding,
context,
unfunded_context,
funding_negotiation_context,
funding_tx_locktime,
funding_negotiation_context: Some(funding_negotiation_context),
interactive_tx_constructor: None,
};
Ok(chan)
Expand DownExpand Up@@ -14096,29 +14112,28 @@ where
},
funding_feerate_sat_per_1000_weight: self.context.feerate_per_kw,
second_per_commitment_point,
locktime: self.funding_negotiation_context.funding_tx_locktime.to_consensus_u32(),
locktime: self.funding_tx_locktime.to_consensus_u32(),
require_confirmed_inputs: None,
}
}

/// Creates a new dual-funded channel from a remote side's request for one.
/// Assumes chain_hash has already been checked and corresponds with what we expect!
/// TODO(dual_funding): Allow contributions, pass intended amount and inputs
#[allow(dead_code)] // TODO(dual_funding): Remove once V2 channels is enabled.
#[rustfmt::skip]
pub fn new_inbound<ES: Deref, F: Deref, L: Deref>(
fee_estimator: &LowerBoundedFeeEstimator<F>, entropy_source: &ES, signer_provider: &SP,
holder_node_id: PublicKey, counterparty_node_id: PublicKey, our_supported_features: &ChannelTypeFeatures,
their_features: &InitFeatures, msg: &msgs::OpenChannelV2,
user_id: u128, config: &UserConfig, current_chain_height: u32, logger: &L,
their_features: &InitFeatures, msg: &msgs::OpenChannelV2, user_id: u128, config: &UserConfig,
current_chain_height: u32, logger: &L, our_funding_contribution: Amount,
our_funding_inputs: Vec<FundingTxInput>, change_script: Option<ScriptBuf>,
) -> Result<Self, ChannelError>
where ES::Target: EntropySource,
F::Target: FeeEstimator,
L::Target: Logger,
{
// TODO(dual_funding): Take these as input once supported
let (our_funding_contribution, our_funding_contribution_sats) = (SignedAmount::ZERO, 0u64);
let our_funding_inputs = Vec::new();
debug_assert!(our_funding_contribution <= Amount::MAX_MONEY);
let our_funding_contribution_sats = our_funding_contribution.to_sat();

let channel_value_satoshis =
our_funding_contribution_sats.saturating_add(msg.common_fields.funding_satoshis);
Expand DownExpand Up@@ -14161,39 +14176,33 @@ where
&funding.get_counterparty_pubkeys().revocation_basepoint);
context.channel_id = channel_id;

let funding_tx_locktime = LockTime::from_consensus(msg.locktime);
let funding_negotiation_context = FundingNegotiationContext {
is_initiator: false,
our_funding_contribution,
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
our_funding_contribution: our_funding_contribution
.to_signed()
.expect("our_funding_contribution should not be greater than Amount::MAX_MONEY"),
funding_tx_locktime,
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
shared_funding_input: None,
our_funding_inputs: our_funding_inputs.clone(),
our_funding_outputs: Vec::new(),
change_script: None,
};
let shared_funding_output = TxOut {
value: Amount::from_sat(funding.get_value_satoshis()),
script_pubkey: funding.get_funding_redeemscript().to_p2wsh(),
change_script,
};

let interactive_tx_constructor = Some(InteractiveTxConstructor::new(
InteractiveTxConstructorArgs {
let mut interactive_tx_constructor = funding_negotiation_context
.into_interactive_tx_constructor(
&context,
&funding,
signer_provider,
entropy_source,
holder_node_id,
counterparty_node_id,
channel_id: context.channel_id,
feerate_sat_per_kw: funding_negotiation_context.funding_feerate_sat_per_1000_weight,
funding_tx_locktime: funding_negotiation_context.funding_tx_locktime,
is_initiator: false,
inputs_to_contribute: our_funding_inputs,
shared_funding_input: None,
shared_funding_output: SharedOwnedOutput::new(shared_funding_output, our_funding_contribution_sats),
outputs_to_contribute: funding_negotiation_context.our_funding_outputs.clone(),
}
).map_err(|err| {
let reason = ClosureReason::ProcessingError { err: err.reason.to_string() };
ChannelError::Close((err.reason.to_string(), reason))
})?);
)
.map_err(|err| {
let reason = ClosureReason::ProcessingError { err: err.reason.to_string() };
ChannelError::Close((err.reason.to_string(), reason))
})?;
debug_assert!(interactive_tx_constructor.take_initiator_first_message().is_none());

let unfunded_context = UnfundedChannelContext {
unfunded_channel_age_ticks: 0,
Expand All@@ -14202,9 +14211,10 @@ where
Ok(Self {
funding,
context,
funding_negotiation_context,
interactive_tx_constructor,
unfunded_context,
funding_tx_locktime,
funding_negotiation_context: None,
interactive_tx_constructor: Some(interactive_tx_constructor),
Comment on lines +14216 to +14217

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would be nice to reuse FundingNegotiation here, but it seems unclear whether the last AwaitingSignatures state can be adapted to the initial dual funding state

})
}

Expand DownExpand Up@@ -14267,8 +14277,7 @@ where
}),
channel_type: Some(self.funding.get_channel_type().clone()),
},
funding_satoshis: self.funding_negotiation_context.our_funding_contribution.to_sat()
as u64,
funding_satoshis: self.our_funding_contribution().to_sat(),
second_per_commitment_point,
require_confirmed_inputs: None,
}
Expand All@@ -14283,6 +14292,10 @@ where
pub fn get_accept_channel_v2_message(&self) -> msgs::AcceptChannelV2 {
self.generate_accept_channel_v2_message()
}

pub fn our_funding_contribution(&self) -> Amount {
Amount::from_sat(self.funding.value_to_self_msat / 1000)
}
}

// Unfunded channel utilities
Expand Down
77 changes: 69 additions & 8 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -30,7 +30,7 @@ use bitcoin::hashes::{Hash, HashEngine, HmacEngine};

use bitcoin::secp256k1::Secp256k1;
use bitcoin::secp256k1::{PublicKey, SecretKey};
use bitcoin::{secp256k1, Sequence, SignedAmount};
use bitcoin::{secp256k1, Amount, ScriptBuf, Sequence};

use crate::blinded_path::message::{
AsyncPaymentsContext, BlindedMessagePath, MessageForwardNode, OffersContext,
Expand DownExpand Up@@ -65,7 +65,7 @@ use crate::ln::channel::{
WithChannelContext,
};
use crate::ln::channel_state::ChannelDetails;
use crate::ln::funding::SpliceContribution;
use crate::ln::funding::{FundingTxInput, SpliceContribution};
use crate::ln::inbound_payment;
use crate::ln::interactivetxs::InteractiveTxMessageSend;
use crate::ln::msgs;
Expand DownExpand Up@@ -9814,6 +9814,9 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
false,
user_channel_id,
config_overrides,
Amount::ZERO,
vec![],
None,
)
}

Expand DownExpand Up@@ -9845,15 +9848,73 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
true,
user_channel_id,
config_overrides,
Amount::ZERO,
vec![],
None,
)
}

/// Accepts a request to open a dual-funded channel with a contribution provided after an
/// [`Event::OpenChannelRequest`].
///
/// The [`Event::OpenChannelRequest::channel_negotiation_type`] field will indicate the open channel
/// request is for a dual-funded channel when the variant is [`InboundChannelFunds::DualFunded`].
///
/// The `temporary_channel_id` parameter indicates which inbound channel should be accepted,
/// and the `counterparty_node_id` parameter is the id of the peer that 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_channel_*` call.
///
/// The `funding_inputs` parameter provides which UTXOs to use for `our_funding_contribution`
/// along with the corresponding satisfaction weight. They must be able to cover any fees needed
/// to pay for the contributed weight to the funding transaction. This includes the witnesses
/// provided through calling [`ChannelManager::funding_transaction_signed`] after receiving
/// [`Event::FundingTransactionReadyForSigning`].
///
/// 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://diyhpl.us/~bryan/irc/bitcoin/bitcoin-dev/linuxfoundation-pipermail/lightning-dev/2023-May/003922.txt
///
/// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
/// [`Event::OpenChannelRequest::channel_negotiation_type`]: events::Event::OpenChannelRequest::channel_negotiation_type
/// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
/// [`Event::FundingTransactionReadyForSigning`]: events::Event::FundingTransactionReadyForSigning
/// [`ChannelManager::funding_transaction_signed`]: ChannelManager::funding_transaction_signed
pub fn accept_inbound_channel_with_contribution(
&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey,
user_channel_id: u128, config_overrides: Option<ChannelConfigOverrides>,
our_funding_contribution: Amount, funding_inputs: Vec<FundingTxInput>,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're also allowed to include outputs, behaving similar to the mixed mode splice, so maybe it's worth waiting until we figure that out in #4261 so we can adopt it here?

change_script: Option<ScriptBuf>,
) -> Result<(), APIError> {
self.do_accept_inbound_channel(
temporary_channel_id,
counterparty_node_id,
false,
user_channel_id,
config_overrides,
our_funding_contribution,
funding_inputs,
change_script,
)
}

/// TODO(dual_funding): Allow contributions, pass intended amount and inputs
#[rustfmt::skip]
fn do_accept_inbound_channel(
&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, accept_0conf: bool,
user_channel_id: u128, config_overrides: Option<ChannelConfigOverrides>
&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey,
accept_0conf: bool, user_channel_id: u128, config_overrides: Option<ChannelConfigOverrides>,
our_funding_contribution: Amount, funding_inputs: Vec<FundingTxInput>,
change_script: Option<ScriptBuf>,
) -> Result<(), APIError> {
if our_funding_contribution > Amount::MAX_MONEY {
return Err(APIError::APIMisuseError {
err: format!("the funding contribution must be smaller than the total bitcoin supply, it was {}", our_funding_contribution)
});
}

let mut config = self.config.read().unwrap().clone();

Expand DownExpand Up@@ -9911,7 +9972,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
&self.channel_type_features(), &peer_state.latest_features,
&open_channel_msg,
user_channel_id, &config, best_block_height,
&self.logger,
&self.logger, our_funding_contribution, funding_inputs, change_script,
).map_err(|e| {
let channel_id = open_channel_msg.common_fields.temporary_channel_id;
MsgHandleErrInternal::from_chan_no_close(e, channel_id)
Expand DownExpand Up@@ -10055,7 +10116,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/

// Inbound V2 channels with contributed inputs are not considered unfunded.
if let Some(unfunded_chan) = chan.as_unfunded_v2() {
if unfunded_chan.funding_negotiation_context.our_funding_contribution > SignedAmount::ZERO {
if unfunded_chan.our_funding_contribution() > Amount::ZERO {
continue;
}
}
Expand DownExpand Up@@ -10197,7 +10258,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
&self.fee_estimator, &self.entropy_source, &self.signer_provider,
self.get_our_node_id(), *counterparty_node_id, &self.channel_type_features(),
&peer_state.latest_features, msg, user_channel_id,
&self.config.read().unwrap(), best_block_height, &self.logger,
&self.config.read().unwrap(), best_block_height, &self.logger, Amount::ZERO, vec![], None,
).map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.common_fields.temporary_channel_id))?;
let message_send_event = MessageSendEvent::SendAcceptChannelV2 {
node_id: *counterparty_node_id,
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 49 additions & 36 deletions lightning/src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -6314,6 +6314,19 @@ where
}
}

#[cfg(all(test))]
pub fn get_initial_counterparty_commitment_signatures_for_test<L: Deref>(
&mut self, funding: &mut FundingScope, logger: &L,
counterparty_next_commitment_point_override: PublicKey,
) -> Option<(Signature, Vec<Signature>)>
where
SP::Target: SignerProvider,
L::Target: Logger,
{
self.counterparty_next_commitment_point = Some(counterparty_next_commitment_point_override);
self.get_initial_counterparty_commitment_signatures(funding, logger)
}

fn check_funding_meets_minimum_depth(&self, funding: &FundingScope, height: u32) -> bool {
let minimum_depth = self
.minimum_depth(funding)
Expand DownExpand Up@@ -13946,7 +13959,9 @@ where
pub funding: FundingScope,
pub context: ChannelContext<SP>,
pub unfunded_context: UnfundedChannelContext,
pub funding_negotiation_context: FundingNegotiationContext,
funding_tx_locktime: LockTime,
#[allow(unused)] // TODO(dual_funding): Remove once initiating V2 channels is enabled.
pub funding_negotiation_context: Option<FundingNegotiationContext>,
/// The current interactive transaction construction session under negotiation.
pub interactive_tx_constructor: Option<InteractiveTxConstructor>,
}
Expand DownExpand Up@@ -14021,7 +14036,8 @@ where
funding,
context,
unfunded_context,
funding_negotiation_context,
funding_tx_locktime,
funding_negotiation_context: Some(funding_negotiation_context),
interactive_tx_constructor: None,
};
Ok(chan)
Expand DownExpand Up@@ -14096,29 +14112,28 @@ where
},
funding_feerate_sat_per_1000_weight: self.context.feerate_per_kw,
second_per_commitment_point,
locktime: self.funding_negotiation_context.funding_tx_locktime.to_consensus_u32(),
locktime: self.funding_tx_locktime.to_consensus_u32(),
require_confirmed_inputs: None,
}
}

/// Creates a new dual-funded channel from a remote side's request for one.
/// Assumes chain_hash has already been checked and corresponds with what we expect!
/// TODO(dual_funding): Allow contributions, pass intended amount and inputs
#[allow(dead_code)] // TODO(dual_funding): Remove once V2 channels is enabled.
#[rustfmt::skip]
pub fn new_inbound<ES: Deref, F: Deref, L: Deref>(
fee_estimator: &LowerBoundedFeeEstimator<F>, entropy_source: &ES, signer_provider: &SP,
holder_node_id: PublicKey, counterparty_node_id: PublicKey, our_supported_features: &ChannelTypeFeatures,
their_features: &InitFeatures, msg: &msgs::OpenChannelV2,
user_id: u128, config: &UserConfig, current_chain_height: u32, logger: &L,
their_features: &InitFeatures, msg: &msgs::OpenChannelV2, user_id: u128, config: &UserConfig,
current_chain_height: u32, logger: &L, our_funding_contribution: Amount,
our_funding_inputs: Vec<FundingTxInput>, change_script: Option<ScriptBuf>,
) -> Result<Self, ChannelError>
where ES::Target: EntropySource,
F::Target: FeeEstimator,
L::Target: Logger,
{
// TODO(dual_funding): Take these as input once supported
let (our_funding_contribution, our_funding_contribution_sats) = (SignedAmount::ZERO, 0u64);
let our_funding_inputs = Vec::new();
debug_assert!(our_funding_contribution <= Amount::MAX_MONEY);
let our_funding_contribution_sats = our_funding_contribution.to_sat();

let channel_value_satoshis =
our_funding_contribution_sats.saturating_add(msg.common_fields.funding_satoshis);
Expand DownExpand Up@@ -14161,39 +14176,33 @@ where
&funding.get_counterparty_pubkeys().revocation_basepoint);
context.channel_id = channel_id;

let funding_tx_locktime = LockTime::from_consensus(msg.locktime);
let funding_negotiation_context = FundingNegotiationContext {
is_initiator: false,
our_funding_contribution,
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
our_funding_contribution: our_funding_contribution
.to_signed()
.expect("our_funding_contribution should not be greater than Amount::MAX_MONEY"),
funding_tx_locktime,
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
shared_funding_input: None,
our_funding_inputs: our_funding_inputs.clone(),
our_funding_outputs: Vec::new(),
change_script: None,
};
let shared_funding_output = TxOut {
value: Amount::from_sat(funding.get_value_satoshis()),
script_pubkey: funding.get_funding_redeemscript().to_p2wsh(),
change_script,
};

let interactive_tx_constructor = Some(InteractiveTxConstructor::new(
InteractiveTxConstructorArgs {
let mut interactive_tx_constructor = funding_negotiation_context
.into_interactive_tx_constructor(
&context,
&funding,
signer_provider,
entropy_source,
holder_node_id,
counterparty_node_id,
channel_id: context.channel_id,
feerate_sat_per_kw: funding_negotiation_context.funding_feerate_sat_per_1000_weight,
funding_tx_locktime: funding_negotiation_context.funding_tx_locktime,
is_initiator: false,
inputs_to_contribute: our_funding_inputs,
shared_funding_input: None,
shared_funding_output: SharedOwnedOutput::new(shared_funding_output, our_funding_contribution_sats),
outputs_to_contribute: funding_negotiation_context.our_funding_outputs.clone(),
}
).map_err(|err| {
let reason = ClosureReason::ProcessingError { err: err.reason.to_string() };
ChannelError::Close((err.reason.to_string(), reason))
})?);
)
.map_err(|err| {
let reason = ClosureReason::ProcessingError { err: err.reason.to_string() };
ChannelError::Close((err.reason.to_string(), reason))
})?;
debug_assert!(interactive_tx_constructor.take_initiator_first_message().is_none());

let unfunded_context = UnfundedChannelContext {
unfunded_channel_age_ticks: 0,
Expand All@@ -14202,9 +14211,10 @@ where
Ok(Self {
funding,
context,
funding_negotiation_context,
interactive_tx_constructor,
unfunded_context,
funding_tx_locktime,
funding_negotiation_context: None,
interactive_tx_constructor: Some(interactive_tx_constructor),
Comment on lines +14216 to +14217

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would be nice to reuse FundingNegotiation here, but it seems unclear whether the last AwaitingSignatures state can be adapted to the initial dual funding state

})
}

Expand DownExpand Up@@ -14267,8 +14277,7 @@ where
}),
channel_type: Some(self.funding.get_channel_type().clone()),
},
funding_satoshis: self.funding_negotiation_context.our_funding_contribution.to_sat()
as u64,
funding_satoshis: self.our_funding_contribution().to_sat(),
second_per_commitment_point,
require_confirmed_inputs: None,
}
Expand All@@ -14283,6 +14292,10 @@ where
pub fn get_accept_channel_v2_message(&self) -> msgs::AcceptChannelV2 {
self.generate_accept_channel_v2_message()
}

pub fn our_funding_contribution(&self) -> Amount {
Amount::from_sat(self.funding.value_to_self_msat / 1000)
}
}

// Unfunded channel utilities
Expand Down
77 changes: 69 additions & 8 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -30,7 +30,7 @@ use bitcoin::hashes::{Hash, HashEngine, HmacEngine};

use bitcoin::secp256k1::Secp256k1;
use bitcoin::secp256k1::{PublicKey, SecretKey};
use bitcoin::{secp256k1, Sequence, SignedAmount};
use bitcoin::{secp256k1, Amount, ScriptBuf, Sequence};

use crate::blinded_path::message::{
AsyncPaymentsContext, BlindedMessagePath, MessageForwardNode, OffersContext,
Expand DownExpand Up@@ -65,7 +65,7 @@ use crate::ln::channel::{
WithChannelContext,
};
use crate::ln::channel_state::ChannelDetails;
use crate::ln::funding::SpliceContribution;
use crate::ln::funding::{FundingTxInput, SpliceContribution};
use crate::ln::inbound_payment;
use crate::ln::interactivetxs::InteractiveTxMessageSend;
use crate::ln::msgs;
Expand DownExpand Up@@ -9814,6 +9814,9 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
false,
user_channel_id,
config_overrides,
Amount::ZERO,
vec![],
None,
)
}

Expand DownExpand Up@@ -9845,15 +9848,73 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
true,
user_channel_id,
config_overrides,
Amount::ZERO,
vec![],
None,
)
}

/// Accepts a request to open a dual-funded channel with a contribution provided after an
/// [`Event::OpenChannelRequest`].
///
/// The [`Event::OpenChannelRequest::channel_negotiation_type`] field will indicate the open channel
/// request is for a dual-funded channel when the variant is [`InboundChannelFunds::DualFunded`].
///
/// The `temporary_channel_id` parameter indicates which inbound channel should be accepted,
/// and the `counterparty_node_id` parameter is the id of the peer that 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_channel_*` call.
///
/// The `funding_inputs` parameter provides which UTXOs to use for `our_funding_contribution`
/// along with the corresponding satisfaction weight. They must be able to cover any fees needed
/// to pay for the contributed weight to the funding transaction. This includes the witnesses
/// provided through calling [`ChannelManager::funding_transaction_signed`] after receiving
/// [`Event::FundingTransactionReadyForSigning`].
///
/// 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://diyhpl.us/~bryan/irc/bitcoin/bitcoin-dev/linuxfoundation-pipermail/lightning-dev/2023-May/003922.txt
///
/// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
/// [`Event::OpenChannelRequest::channel_negotiation_type`]: events::Event::OpenChannelRequest::channel_negotiation_type
/// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
/// [`Event::FundingTransactionReadyForSigning`]: events::Event::FundingTransactionReadyForSigning
/// [`ChannelManager::funding_transaction_signed`]: ChannelManager::funding_transaction_signed
pub fn accept_inbound_channel_with_contribution(
&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey,
user_channel_id: u128, config_overrides: Option<ChannelConfigOverrides>,
our_funding_contribution: Amount, funding_inputs: Vec<FundingTxInput>,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're also allowed to include outputs, behaving similar to the mixed mode splice, so maybe it's worth waiting until we figure that out in #4261 so we can adopt it here?

change_script: Option<ScriptBuf>,
) -> Result<(), APIError> {
self.do_accept_inbound_channel(
temporary_channel_id,
counterparty_node_id,
false,
user_channel_id,
config_overrides,
our_funding_contribution,
funding_inputs,
change_script,
)
}

/// TODO(dual_funding): Allow contributions, pass intended amount and inputs
#[rustfmt::skip]
fn do_accept_inbound_channel(
&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, accept_0conf: bool,
user_channel_id: u128, config_overrides: Option<ChannelConfigOverrides>
&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey,
accept_0conf: bool, user_channel_id: u128, config_overrides: Option<ChannelConfigOverrides>,
our_funding_contribution: Amount, funding_inputs: Vec<FundingTxInput>,
change_script: Option<ScriptBuf>,
) -> Result<(), APIError> {
if our_funding_contribution > Amount::MAX_MONEY {
return Err(APIError::APIMisuseError {
err: format!("the funding contribution must be smaller than the total bitcoin supply, it was {}", our_funding_contribution)
});
}

let mut config = self.config.read().unwrap().clone();

Expand DownExpand Up@@ -9911,7 +9972,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
&self.channel_type_features(), &peer_state.latest_features,
&open_channel_msg,
user_channel_id, &config, best_block_height,
&self.logger,
&self.logger, our_funding_contribution, funding_inputs, change_script,
).map_err(|e| {
let channel_id = open_channel_msg.common_fields.temporary_channel_id;
MsgHandleErrInternal::from_chan_no_close(e, channel_id)
Expand DownExpand Up@@ -10055,7 +10116,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/

// Inbound V2 channels with contributed inputs are not considered unfunded.
if let Some(unfunded_chan) = chan.as_unfunded_v2() {
if unfunded_chan.funding_negotiation_context.our_funding_contribution > SignedAmount::ZERO {
if unfunded_chan.our_funding_contribution() > Amount::ZERO {
continue;
}
}
Expand DownExpand Up@@ -10197,7 +10258,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
&self.fee_estimator, &self.entropy_source, &self.signer_provider,
self.get_our_node_id(), *counterparty_node_id, &self.channel_type_features(),
&peer_state.latest_features, msg, user_channel_id,
&self.config.read().unwrap(), best_block_height, &self.logger,
&self.config.read().unwrap(), best_block_height, &self.logger, Amount::ZERO, vec![], None,
).map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.common_fields.temporary_channel_id))?;
let message_send_event = MessageSendEvent::SendAcceptChannelV2 {
node_id: *counterparty_node_id,
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 49 additions & 36 deletions lightning/src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -6314,6 +6314,19 @@ where
}
}

#[cfg(all(test))]
pub fn get_initial_counterparty_commitment_signatures_for_test<L: Deref>(
&mut self, funding: &mut FundingScope, logger: &L,
counterparty_next_commitment_point_override: PublicKey,
) -> Option<(Signature, Vec<Signature>)>
where
SP::Target: SignerProvider,
L::Target: Logger,
{
self.counterparty_next_commitment_point = Some(counterparty_next_commitment_point_override);
self.get_initial_counterparty_commitment_signatures(funding, logger)
}

fn check_funding_meets_minimum_depth(&self, funding: &FundingScope, height: u32) -> bool {
let minimum_depth = self
.minimum_depth(funding)
Expand DownExpand Up@@ -13946,7 +13959,9 @@ where
pub funding: FundingScope,
pub context: ChannelContext<SP>,
pub unfunded_context: UnfundedChannelContext,
pub funding_negotiation_context: FundingNegotiationContext,
funding_tx_locktime: LockTime,
#[allow(unused)] // TODO(dual_funding): Remove once initiating V2 channels is enabled.
pub funding_negotiation_context: Option<FundingNegotiationContext>,
/// The current interactive transaction construction session under negotiation.
pub interactive_tx_constructor: Option<InteractiveTxConstructor>,
}
Expand DownExpand Up@@ -14021,7 +14036,8 @@ where
funding,
context,
unfunded_context,
funding_negotiation_context,
funding_tx_locktime,
funding_negotiation_context: Some(funding_negotiation_context),
interactive_tx_constructor: None,
};
Ok(chan)
Expand DownExpand Up@@ -14096,29 +14112,28 @@ where
},
funding_feerate_sat_per_1000_weight: self.context.feerate_per_kw,
second_per_commitment_point,
locktime: self.funding_negotiation_context.funding_tx_locktime.to_consensus_u32(),
locktime: self.funding_tx_locktime.to_consensus_u32(),
require_confirmed_inputs: None,
}
}

/// Creates a new dual-funded channel from a remote side's request for one.
/// Assumes chain_hash has already been checked and corresponds with what we expect!
/// TODO(dual_funding): Allow contributions, pass intended amount and inputs
#[allow(dead_code)] // TODO(dual_funding): Remove once V2 channels is enabled.
#[rustfmt::skip]
pub fn new_inbound<ES: Deref, F: Deref, L: Deref>(
fee_estimator: &LowerBoundedFeeEstimator<F>, entropy_source: &ES, signer_provider: &SP,
holder_node_id: PublicKey, counterparty_node_id: PublicKey, our_supported_features: &ChannelTypeFeatures,
their_features: &InitFeatures, msg: &msgs::OpenChannelV2,
user_id: u128, config: &UserConfig, current_chain_height: u32, logger: &L,
their_features: &InitFeatures, msg: &msgs::OpenChannelV2, user_id: u128, config: &UserConfig,
current_chain_height: u32, logger: &L, our_funding_contribution: Amount,
our_funding_inputs: Vec<FundingTxInput>, change_script: Option<ScriptBuf>,
) -> Result<Self, ChannelError>
where ES::Target: EntropySource,
F::Target: FeeEstimator,
L::Target: Logger,
{
// TODO(dual_funding): Take these as input once supported
let (our_funding_contribution, our_funding_contribution_sats) = (SignedAmount::ZERO, 0u64);
let our_funding_inputs = Vec::new();
debug_assert!(our_funding_contribution <= Amount::MAX_MONEY);
let our_funding_contribution_sats = our_funding_contribution.to_sat();

let channel_value_satoshis =
our_funding_contribution_sats.saturating_add(msg.common_fields.funding_satoshis);
Expand DownExpand Up@@ -14161,39 +14176,33 @@ where
&funding.get_counterparty_pubkeys().revocation_basepoint);
context.channel_id = channel_id;

let funding_tx_locktime = LockTime::from_consensus(msg.locktime);
let funding_negotiation_context = FundingNegotiationContext {
is_initiator: false,
our_funding_contribution,
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
our_funding_contribution: our_funding_contribution
.to_signed()
.expect("our_funding_contribution should not be greater than Amount::MAX_MONEY"),
funding_tx_locktime,
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
shared_funding_input: None,
our_funding_inputs: our_funding_inputs.clone(),
our_funding_outputs: Vec::new(),
change_script: None,
};
let shared_funding_output = TxOut {
value: Amount::from_sat(funding.get_value_satoshis()),
script_pubkey: funding.get_funding_redeemscript().to_p2wsh(),
change_script,
};

let interactive_tx_constructor = Some(InteractiveTxConstructor::new(
InteractiveTxConstructorArgs {
let mut interactive_tx_constructor = funding_negotiation_context
.into_interactive_tx_constructor(
&context,
&funding,
signer_provider,
entropy_source,
holder_node_id,
counterparty_node_id,
channel_id: context.channel_id,
feerate_sat_per_kw: funding_negotiation_context.funding_feerate_sat_per_1000_weight,
funding_tx_locktime: funding_negotiation_context.funding_tx_locktime,
is_initiator: false,
inputs_to_contribute: our_funding_inputs,
shared_funding_input: None,
shared_funding_output: SharedOwnedOutput::new(shared_funding_output, our_funding_contribution_sats),
outputs_to_contribute: funding_negotiation_context.our_funding_outputs.clone(),
}
).map_err(|err| {
let reason = ClosureReason::ProcessingError { err: err.reason.to_string() };
ChannelError::Close((err.reason.to_string(), reason))
})?);
)
.map_err(|err| {
let reason = ClosureReason::ProcessingError { err: err.reason.to_string() };
ChannelError::Close((err.reason.to_string(), reason))
})?;
debug_assert!(interactive_tx_constructor.take_initiator_first_message().is_none());

let unfunded_context = UnfundedChannelContext {
unfunded_channel_age_ticks: 0,
Expand All@@ -14202,9 +14211,10 @@ where
Ok(Self {
funding,
context,
funding_negotiation_context,
interactive_tx_constructor,
unfunded_context,
funding_tx_locktime,
funding_negotiation_context: None,
interactive_tx_constructor: Some(interactive_tx_constructor),
Comment on lines +14216 to +14217

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would be nice to reuse FundingNegotiation here, but it seems unclear whether the last AwaitingSignatures state can be adapted to the initial dual funding state

})
}

Expand DownExpand Up@@ -14267,8 +14277,7 @@ where
}),
channel_type: Some(self.funding.get_channel_type().clone()),
},
funding_satoshis: self.funding_negotiation_context.our_funding_contribution.to_sat()
as u64,
funding_satoshis: self.our_funding_contribution().to_sat(),
second_per_commitment_point,
require_confirmed_inputs: None,
}
Expand All@@ -14283,6 +14292,10 @@ where
pub fn get_accept_channel_v2_message(&self) -> msgs::AcceptChannelV2 {
self.generate_accept_channel_v2_message()
}

pub fn our_funding_contribution(&self) -> Amount {
Amount::from_sat(self.funding.value_to_self_msat / 1000)
}
}

// Unfunded channel utilities
Expand Down
77 changes: 69 additions & 8 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -30,7 +30,7 @@ use bitcoin::hashes::{Hash, HashEngine, HmacEngine};

use bitcoin::secp256k1::Secp256k1;
use bitcoin::secp256k1::{PublicKey, SecretKey};
use bitcoin::{secp256k1, Sequence, SignedAmount};
use bitcoin::{secp256k1, Amount, ScriptBuf, Sequence};

use crate::blinded_path::message::{
AsyncPaymentsContext, BlindedMessagePath, MessageForwardNode, OffersContext,
Expand DownExpand Up@@ -65,7 +65,7 @@ use crate::ln::channel::{
WithChannelContext,
};
use crate::ln::channel_state::ChannelDetails;
use crate::ln::funding::SpliceContribution;
use crate::ln::funding::{FundingTxInput, SpliceContribution};
use crate::ln::inbound_payment;
use crate::ln::interactivetxs::InteractiveTxMessageSend;
use crate::ln::msgs;
Expand DownExpand Up@@ -9814,6 +9814,9 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
false,
user_channel_id,
config_overrides,
Amount::ZERO,
vec![],
None,
)
}

Expand DownExpand Up@@ -9845,15 +9848,73 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
true,
user_channel_id,
config_overrides,
Amount::ZERO,
vec![],
None,
)
}

/// Accepts a request to open a dual-funded channel with a contribution provided after an
/// [`Event::OpenChannelRequest`].
///
/// The [`Event::OpenChannelRequest::channel_negotiation_type`] field will indicate the open channel
/// request is for a dual-funded channel when the variant is [`InboundChannelFunds::DualFunded`].
///
/// The `temporary_channel_id` parameter indicates which inbound channel should be accepted,
/// and the `counterparty_node_id` parameter is the id of the peer that 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_channel_*` call.
///
/// The `funding_inputs` parameter provides which UTXOs to use for `our_funding_contribution`
/// along with the corresponding satisfaction weight. They must be able to cover any fees needed
/// to pay for the contributed weight to the funding transaction. This includes the witnesses
/// provided through calling [`ChannelManager::funding_transaction_signed`] after receiving
/// [`Event::FundingTransactionReadyForSigning`].
///
/// 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://diyhpl.us/~bryan/irc/bitcoin/bitcoin-dev/linuxfoundation-pipermail/lightning-dev/2023-May/003922.txt
///
/// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
/// [`Event::OpenChannelRequest::channel_negotiation_type`]: events::Event::OpenChannelRequest::channel_negotiation_type
/// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
/// [`Event::FundingTransactionReadyForSigning`]: events::Event::FundingTransactionReadyForSigning
/// [`ChannelManager::funding_transaction_signed`]: ChannelManager::funding_transaction_signed
pub fn accept_inbound_channel_with_contribution(
&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey,
user_channel_id: u128, config_overrides: Option<ChannelConfigOverrides>,
our_funding_contribution: Amount, funding_inputs: Vec<FundingTxInput>,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're also allowed to include outputs, behaving similar to the mixed mode splice, so maybe it's worth waiting until we figure that out in #4261 so we can adopt it here?

change_script: Option<ScriptBuf>,
) -> Result<(), APIError> {
self.do_accept_inbound_channel(
temporary_channel_id,
counterparty_node_id,
false,
user_channel_id,
config_overrides,
our_funding_contribution,
funding_inputs,
change_script,
)
}

/// TODO(dual_funding): Allow contributions, pass intended amount and inputs
#[rustfmt::skip]
fn do_accept_inbound_channel(
&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, accept_0conf: bool,
user_channel_id: u128, config_overrides: Option<ChannelConfigOverrides>
&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey,
accept_0conf: bool, user_channel_id: u128, config_overrides: Option<ChannelConfigOverrides>,
our_funding_contribution: Amount, funding_inputs: Vec<FundingTxInput>,
change_script: Option<ScriptBuf>,
) -> Result<(), APIError> {
if our_funding_contribution > Amount::MAX_MONEY {
return Err(APIError::APIMisuseError {
err: format!("the funding contribution must be smaller than the total bitcoin supply, it was {}", our_funding_contribution)
});
}

let mut config = self.config.read().unwrap().clone();

Expand DownExpand Up@@ -9911,7 +9972,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
&self.channel_type_features(), &peer_state.latest_features,
&open_channel_msg,
user_channel_id, &config, best_block_height,
&self.logger,
&self.logger, our_funding_contribution, funding_inputs, change_script,
).map_err(|e| {
let channel_id = open_channel_msg.common_fields.temporary_channel_id;
MsgHandleErrInternal::from_chan_no_close(e, channel_id)
Expand DownExpand Up@@ -10055,7 +10116,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/

// Inbound V2 channels with contributed inputs are not considered unfunded.
if let Some(unfunded_chan) = chan.as_unfunded_v2() {
if unfunded_chan.funding_negotiation_context.our_funding_contribution > SignedAmount::ZERO {
if unfunded_chan.our_funding_contribution() > Amount::ZERO {
continue;
}
}
Expand DownExpand Up@@ -10197,7 +10258,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
&self.fee_estimator, &self.entropy_source, &self.signer_provider,
self.get_our_node_id(), *counterparty_node_id, &self.channel_type_features(),
&peer_state.latest_features, msg, user_channel_id,
&self.config.read().unwrap(), best_block_height, &self.logger,
&self.config.read().unwrap(), best_block_height, &self.logger, Amount::ZERO, vec![], None,
).map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.common_fields.temporary_channel_id))?;
let message_send_event = MessageSendEvent::SendAcceptChannelV2 {
node_id: *counterparty_node_id,
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 49 additions & 36 deletions lightning/src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -6314,6 +6314,19 @@ where
}
}

#[cfg(all(test))]
pub fn get_initial_counterparty_commitment_signatures_for_test<L: Deref>(
&mut self, funding: &mut FundingScope, logger: &L,
counterparty_next_commitment_point_override: PublicKey,
) -> Option<(Signature, Vec<Signature>)>
where
SP::Target: SignerProvider,
L::Target: Logger,
{
self.counterparty_next_commitment_point = Some(counterparty_next_commitment_point_override);
self.get_initial_counterparty_commitment_signatures(funding, logger)
}

fn check_funding_meets_minimum_depth(&self, funding: &FundingScope, height: u32) -> bool {
let minimum_depth = self
.minimum_depth(funding)
Expand DownExpand Up@@ -13946,7 +13959,9 @@ where
pub funding: FundingScope,
pub context: ChannelContext<SP>,
pub unfunded_context: UnfundedChannelContext,
pub funding_negotiation_context: FundingNegotiationContext,
funding_tx_locktime: LockTime,
#[allow(unused)] // TODO(dual_funding): Remove once initiating V2 channels is enabled.
pub funding_negotiation_context: Option<FundingNegotiationContext>,
/// The current interactive transaction construction session under negotiation.
pub interactive_tx_constructor: Option<InteractiveTxConstructor>,
}
Expand DownExpand Up@@ -14021,7 +14036,8 @@ where
funding,
context,
unfunded_context,
funding_negotiation_context,
funding_tx_locktime,
funding_negotiation_context: Some(funding_negotiation_context),
interactive_tx_constructor: None,
};
Ok(chan)
Expand DownExpand Up@@ -14096,29 +14112,28 @@ where
},
funding_feerate_sat_per_1000_weight: self.context.feerate_per_kw,
second_per_commitment_point,
locktime: self.funding_negotiation_context.funding_tx_locktime.to_consensus_u32(),
locktime: self.funding_tx_locktime.to_consensus_u32(),
require_confirmed_inputs: None,
}
}

/// Creates a new dual-funded channel from a remote side's request for one.
/// Assumes chain_hash has already been checked and corresponds with what we expect!
/// TODO(dual_funding): Allow contributions, pass intended amount and inputs
#[allow(dead_code)] // TODO(dual_funding): Remove once V2 channels is enabled.
#[rustfmt::skip]
pub fn new_inbound<ES: Deref, F: Deref, L: Deref>(
fee_estimator: &LowerBoundedFeeEstimator<F>, entropy_source: &ES, signer_provider: &SP,
holder_node_id: PublicKey, counterparty_node_id: PublicKey, our_supported_features: &ChannelTypeFeatures,
their_features: &InitFeatures, msg: &msgs::OpenChannelV2,
user_id: u128, config: &UserConfig, current_chain_height: u32, logger: &L,
their_features: &InitFeatures, msg: &msgs::OpenChannelV2, user_id: u128, config: &UserConfig,
current_chain_height: u32, logger: &L, our_funding_contribution: Amount,
our_funding_inputs: Vec<FundingTxInput>, change_script: Option<ScriptBuf>,
) -> Result<Self, ChannelError>
where ES::Target: EntropySource,
F::Target: FeeEstimator,
L::Target: Logger,
{
// TODO(dual_funding): Take these as input once supported
let (our_funding_contribution, our_funding_contribution_sats) = (SignedAmount::ZERO, 0u64);
let our_funding_inputs = Vec::new();
debug_assert!(our_funding_contribution <= Amount::MAX_MONEY);
let our_funding_contribution_sats = our_funding_contribution.to_sat();

let channel_value_satoshis =
our_funding_contribution_sats.saturating_add(msg.common_fields.funding_satoshis);
Expand DownExpand Up@@ -14161,39 +14176,33 @@ where
&funding.get_counterparty_pubkeys().revocation_basepoint);
context.channel_id = channel_id;

let funding_tx_locktime = LockTime::from_consensus(msg.locktime);
let funding_negotiation_context = FundingNegotiationContext {
is_initiator: false,
our_funding_contribution,
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
our_funding_contribution: our_funding_contribution
.to_signed()
.expect("our_funding_contribution should not be greater than Amount::MAX_MONEY"),
funding_tx_locktime,
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
shared_funding_input: None,
our_funding_inputs: our_funding_inputs.clone(),
our_funding_outputs: Vec::new(),
change_script: None,
};
let shared_funding_output = TxOut {
value: Amount::from_sat(funding.get_value_satoshis()),
script_pubkey: funding.get_funding_redeemscript().to_p2wsh(),
change_script,
};

let interactive_tx_constructor = Some(InteractiveTxConstructor::new(
InteractiveTxConstructorArgs {
let mut interactive_tx_constructor = funding_negotiation_context
.into_interactive_tx_constructor(
&context,
&funding,
signer_provider,
entropy_source,
holder_node_id,
counterparty_node_id,
channel_id: context.channel_id,
feerate_sat_per_kw: funding_negotiation_context.funding_feerate_sat_per_1000_weight,
funding_tx_locktime: funding_negotiation_context.funding_tx_locktime,
is_initiator: false,
inputs_to_contribute: our_funding_inputs,
shared_funding_input: None,
shared_funding_output: SharedOwnedOutput::new(shared_funding_output, our_funding_contribution_sats),
outputs_to_contribute: funding_negotiation_context.our_funding_outputs.clone(),
}
).map_err(|err| {
let reason = ClosureReason::ProcessingError { err: err.reason.to_string() };
ChannelError::Close((err.reason.to_string(), reason))
})?);
)
.map_err(|err| {
let reason = ClosureReason::ProcessingError { err: err.reason.to_string() };
ChannelError::Close((err.reason.to_string(), reason))
})?;
debug_assert!(interactive_tx_constructor.take_initiator_first_message().is_none());

let unfunded_context = UnfundedChannelContext {
unfunded_channel_age_ticks: 0,
Expand All@@ -14202,9 +14211,10 @@ where
Ok(Self {
funding,
context,
funding_negotiation_context,
interactive_tx_constructor,
unfunded_context,
funding_tx_locktime,
funding_negotiation_context: None,
interactive_tx_constructor: Some(interactive_tx_constructor),
Comment on lines +14216 to +14217

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would be nice to reuse FundingNegotiation here, but it seems unclear whether the last AwaitingSignatures state can be adapted to the initial dual funding state

})
}

Expand DownExpand Up@@ -14267,8 +14277,7 @@ where
}),
channel_type: Some(self.funding.get_channel_type().clone()),
},
funding_satoshis: self.funding_negotiation_context.our_funding_contribution.to_sat()
as u64,
funding_satoshis: self.our_funding_contribution().to_sat(),
second_per_commitment_point,
require_confirmed_inputs: None,
}
Expand All@@ -14283,6 +14292,10 @@ where
pub fn get_accept_channel_v2_message(&self) -> msgs::AcceptChannelV2 {
self.generate_accept_channel_v2_message()
}

pub fn our_funding_contribution(&self) -> Amount {
Amount::from_sat(self.funding.value_to_self_msat / 1000)
}
}

// Unfunded channel utilities
Expand Down
77 changes: 69 additions & 8 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -30,7 +30,7 @@ use bitcoin::hashes::{Hash, HashEngine, HmacEngine};

use bitcoin::secp256k1::Secp256k1;
use bitcoin::secp256k1::{PublicKey, SecretKey};
use bitcoin::{secp256k1, Sequence, SignedAmount};
use bitcoin::{secp256k1, Amount, ScriptBuf, Sequence};

use crate::blinded_path::message::{
AsyncPaymentsContext, BlindedMessagePath, MessageForwardNode, OffersContext,
Expand DownExpand Up@@ -65,7 +65,7 @@ use crate::ln::channel::{
WithChannelContext,
};
use crate::ln::channel_state::ChannelDetails;
use crate::ln::funding::SpliceContribution;
use crate::ln::funding::{FundingTxInput, SpliceContribution};
use crate::ln::inbound_payment;
use crate::ln::interactivetxs::InteractiveTxMessageSend;
use crate::ln::msgs;
Expand DownExpand Up@@ -9814,6 +9814,9 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
false,
user_channel_id,
config_overrides,
Amount::ZERO,
vec![],
None,
)
}

Expand DownExpand Up@@ -9845,15 +9848,73 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
true,
user_channel_id,
config_overrides,
Amount::ZERO,
vec![],
None,
)
}

/// Accepts a request to open a dual-funded channel with a contribution provided after an
/// [`Event::OpenChannelRequest`].
///
/// The [`Event::OpenChannelRequest::channel_negotiation_type`] field will indicate the open channel
/// request is for a dual-funded channel when the variant is [`InboundChannelFunds::DualFunded`].
///
/// The `temporary_channel_id` parameter indicates which inbound channel should be accepted,
/// and the `counterparty_node_id` parameter is the id of the peer that 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_channel_*` call.
///
/// The `funding_inputs` parameter provides which UTXOs to use for `our_funding_contribution`
/// along with the corresponding satisfaction weight. They must be able to cover any fees needed
/// to pay for the contributed weight to the funding transaction. This includes the witnesses
/// provided through calling [`ChannelManager::funding_transaction_signed`] after receiving
/// [`Event::FundingTransactionReadyForSigning`].
///
/// 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://diyhpl.us/~bryan/irc/bitcoin/bitcoin-dev/linuxfoundation-pipermail/lightning-dev/2023-May/003922.txt
///
/// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
/// [`Event::OpenChannelRequest::channel_negotiation_type`]: events::Event::OpenChannelRequest::channel_negotiation_type
/// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
/// [`Event::FundingTransactionReadyForSigning`]: events::Event::FundingTransactionReadyForSigning
/// [`ChannelManager::funding_transaction_signed`]: ChannelManager::funding_transaction_signed
pub fn accept_inbound_channel_with_contribution(
&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey,
user_channel_id: u128, config_overrides: Option<ChannelConfigOverrides>,
our_funding_contribution: Amount, funding_inputs: Vec<FundingTxInput>,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're also allowed to include outputs, behaving similar to the mixed mode splice, so maybe it's worth waiting until we figure that out in #4261 so we can adopt it here?

change_script: Option<ScriptBuf>,
) -> Result<(), APIError> {
self.do_accept_inbound_channel(
temporary_channel_id,
counterparty_node_id,
false,
user_channel_id,
config_overrides,
our_funding_contribution,
funding_inputs,
change_script,
)
}

/// TODO(dual_funding): Allow contributions, pass intended amount and inputs
#[rustfmt::skip]
fn do_accept_inbound_channel(
&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, accept_0conf: bool,
user_channel_id: u128, config_overrides: Option<ChannelConfigOverrides>
&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey,
accept_0conf: bool, user_channel_id: u128, config_overrides: Option<ChannelConfigOverrides>,
our_funding_contribution: Amount, funding_inputs: Vec<FundingTxInput>,
change_script: Option<ScriptBuf>,
) -> Result<(), APIError> {
if our_funding_contribution > Amount::MAX_MONEY {
return Err(APIError::APIMisuseError {
err: format!("the funding contribution must be smaller than the total bitcoin supply, it was {}", our_funding_contribution)
});
}

let mut config = self.config.read().unwrap().clone();

Expand DownExpand Up@@ -9911,7 +9972,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
&self.channel_type_features(), &peer_state.latest_features,
&open_channel_msg,
user_channel_id, &config, best_block_height,
&self.logger,
&self.logger, our_funding_contribution, funding_inputs, change_script,
).map_err(|e| {
let channel_id = open_channel_msg.common_fields.temporary_channel_id;
MsgHandleErrInternal::from_chan_no_close(e, channel_id)
Expand DownExpand Up@@ -10055,7 +10116,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/

// Inbound V2 channels with contributed inputs are not considered unfunded.
if let Some(unfunded_chan) = chan.as_unfunded_v2() {
if unfunded_chan.funding_negotiation_context.our_funding_contribution > SignedAmount::ZERO {
if unfunded_chan.our_funding_contribution() > Amount::ZERO {
continue;
}
}
Expand DownExpand Up@@ -10197,7 +10258,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
&self.fee_estimator, &self.entropy_source, &self.signer_provider,
self.get_our_node_id(), *counterparty_node_id, &self.channel_type_features(),
&peer_state.latest_features, msg, user_channel_id,
&self.config.read().unwrap(), best_block_height, &self.logger,
&self.config.read().unwrap(), best_block_height, &self.logger, Amount::ZERO, vec![], None,
).map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.common_fields.temporary_channel_id))?;
let message_send_event = MessageSendEvent::SendAcceptChannelV2 {
node_id: *counterparty_node_id,
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 49 additions & 36 deletions lightning/src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -6314,6 +6314,19 @@ where
}
}

#[cfg(all(test))]
pub fn get_initial_counterparty_commitment_signatures_for_test<L: Deref>(
&mut self, funding: &mut FundingScope, logger: &L,
counterparty_next_commitment_point_override: PublicKey,
) -> Option<(Signature, Vec<Signature>)>
where
SP::Target: SignerProvider,
L::Target: Logger,
{
self.counterparty_next_commitment_point = Some(counterparty_next_commitment_point_override);
self.get_initial_counterparty_commitment_signatures(funding, logger)
}

fn check_funding_meets_minimum_depth(&self, funding: &FundingScope, height: u32) -> bool {
let minimum_depth = self
.minimum_depth(funding)
Expand DownExpand Up@@ -13946,7 +13959,9 @@ where
pub funding: FundingScope,
pub context: ChannelContext<SP>,
pub unfunded_context: UnfundedChannelContext,
pub funding_negotiation_context: FundingNegotiationContext,
funding_tx_locktime: LockTime,
#[allow(unused)] // TODO(dual_funding): Remove once initiating V2 channels is enabled.
pub funding_negotiation_context: Option<FundingNegotiationContext>,
/// The current interactive transaction construction session under negotiation.
pub interactive_tx_constructor: Option<InteractiveTxConstructor>,
}
Expand DownExpand Up@@ -14021,7 +14036,8 @@ where
funding,
context,
unfunded_context,
funding_negotiation_context,
funding_tx_locktime,
funding_negotiation_context: Some(funding_negotiation_context),
interactive_tx_constructor: None,
};
Ok(chan)
Expand DownExpand Up@@ -14096,29 +14112,28 @@ where
},
funding_feerate_sat_per_1000_weight: self.context.feerate_per_kw,
second_per_commitment_point,
locktime: self.funding_negotiation_context.funding_tx_locktime.to_consensus_u32(),
locktime: self.funding_tx_locktime.to_consensus_u32(),
require_confirmed_inputs: None,
}
}

/// Creates a new dual-funded channel from a remote side's request for one.
/// Assumes chain_hash has already been checked and corresponds with what we expect!
/// TODO(dual_funding): Allow contributions, pass intended amount and inputs
#[allow(dead_code)] // TODO(dual_funding): Remove once V2 channels is enabled.
#[rustfmt::skip]
pub fn new_inbound<ES: Deref, F: Deref, L: Deref>(
fee_estimator: &LowerBoundedFeeEstimator<F>, entropy_source: &ES, signer_provider: &SP,
holder_node_id: PublicKey, counterparty_node_id: PublicKey, our_supported_features: &ChannelTypeFeatures,
their_features: &InitFeatures, msg: &msgs::OpenChannelV2,
user_id: u128, config: &UserConfig, current_chain_height: u32, logger: &L,
their_features: &InitFeatures, msg: &msgs::OpenChannelV2, user_id: u128, config: &UserConfig,
current_chain_height: u32, logger: &L, our_funding_contribution: Amount,
our_funding_inputs: Vec<FundingTxInput>, change_script: Option<ScriptBuf>,
) -> Result<Self, ChannelError>
where ES::Target: EntropySource,
F::Target: FeeEstimator,
L::Target: Logger,
{
// TODO(dual_funding): Take these as input once supported
let (our_funding_contribution, our_funding_contribution_sats) = (SignedAmount::ZERO, 0u64);
let our_funding_inputs = Vec::new();
debug_assert!(our_funding_contribution <= Amount::MAX_MONEY);
let our_funding_contribution_sats = our_funding_contribution.to_sat();

let channel_value_satoshis =
our_funding_contribution_sats.saturating_add(msg.common_fields.funding_satoshis);
Expand DownExpand Up@@ -14161,39 +14176,33 @@ where
&funding.get_counterparty_pubkeys().revocation_basepoint);
context.channel_id = channel_id;

let funding_tx_locktime = LockTime::from_consensus(msg.locktime);
let funding_negotiation_context = FundingNegotiationContext {
is_initiator: false,
our_funding_contribution,
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
our_funding_contribution: our_funding_contribution
.to_signed()
.expect("our_funding_contribution should not be greater than Amount::MAX_MONEY"),
funding_tx_locktime,
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
shared_funding_input: None,
our_funding_inputs: our_funding_inputs.clone(),
our_funding_outputs: Vec::new(),
change_script: None,
};
let shared_funding_output = TxOut {
value: Amount::from_sat(funding.get_value_satoshis()),
script_pubkey: funding.get_funding_redeemscript().to_p2wsh(),
change_script,
};

let interactive_tx_constructor = Some(InteractiveTxConstructor::new(
InteractiveTxConstructorArgs {
let mut interactive_tx_constructor = funding_negotiation_context
.into_interactive_tx_constructor(
&context,
&funding,
signer_provider,
entropy_source,
holder_node_id,
counterparty_node_id,
channel_id: context.channel_id,
feerate_sat_per_kw: funding_negotiation_context.funding_feerate_sat_per_1000_weight,
funding_tx_locktime: funding_negotiation_context.funding_tx_locktime,
is_initiator: false,
inputs_to_contribute: our_funding_inputs,
shared_funding_input: None,
shared_funding_output: SharedOwnedOutput::new(shared_funding_output, our_funding_contribution_sats),
outputs_to_contribute: funding_negotiation_context.our_funding_outputs.clone(),
}
).map_err(|err| {
let reason = ClosureReason::ProcessingError { err: err.reason.to_string() };
ChannelError::Close((err.reason.to_string(), reason))
})?);
)
.map_err(|err| {
let reason = ClosureReason::ProcessingError { err: err.reason.to_string() };
ChannelError::Close((err.reason.to_string(), reason))
})?;
debug_assert!(interactive_tx_constructor.take_initiator_first_message().is_none());

let unfunded_context = UnfundedChannelContext {
unfunded_channel_age_ticks: 0,
Expand All@@ -14202,9 +14211,10 @@ where
Ok(Self {
funding,
context,
funding_negotiation_context,
interactive_tx_constructor,
unfunded_context,
funding_tx_locktime,
funding_negotiation_context: None,
interactive_tx_constructor: Some(interactive_tx_constructor),
Comment on lines +14216 to +14217

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would be nice to reuse FundingNegotiation here, but it seems unclear whether the last AwaitingSignatures state can be adapted to the initial dual funding state

})
}

Expand DownExpand Up@@ -14267,8 +14277,7 @@ where
}),
channel_type: Some(self.funding.get_channel_type().clone()),
},
funding_satoshis: self.funding_negotiation_context.our_funding_contribution.to_sat()
as u64,
funding_satoshis: self.our_funding_contribution().to_sat(),
second_per_commitment_point,
require_confirmed_inputs: None,
}
Expand All@@ -14283,6 +14292,10 @@ where
pub fn get_accept_channel_v2_message(&self) -> msgs::AcceptChannelV2 {
self.generate_accept_channel_v2_message()
}

pub fn our_funding_contribution(&self) -> Amount {
Amount::from_sat(self.funding.value_to_self_msat / 1000)
}
}

// Unfunded channel utilities
Expand Down
77 changes: 69 additions & 8 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -30,7 +30,7 @@ use bitcoin::hashes::{Hash, HashEngine, HmacEngine};

use bitcoin::secp256k1::Secp256k1;
use bitcoin::secp256k1::{PublicKey, SecretKey};
use bitcoin::{secp256k1, Sequence, SignedAmount};
use bitcoin::{secp256k1, Amount, ScriptBuf, Sequence};

use crate::blinded_path::message::{
AsyncPaymentsContext, BlindedMessagePath, MessageForwardNode, OffersContext,
Expand DownExpand Up@@ -65,7 +65,7 @@ use crate::ln::channel::{
WithChannelContext,
};
use crate::ln::channel_state::ChannelDetails;
use crate::ln::funding::SpliceContribution;
use crate::ln::funding::{FundingTxInput, SpliceContribution};
use crate::ln::inbound_payment;
use crate::ln::interactivetxs::InteractiveTxMessageSend;
use crate::ln::msgs;
Expand DownExpand Up@@ -9814,6 +9814,9 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
false,
user_channel_id,
config_overrides,
Amount::ZERO,
vec![],
None,
)
}

Expand DownExpand Up@@ -9845,15 +9848,73 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
true,
user_channel_id,
config_overrides,
Amount::ZERO,
vec![],
None,
)
}

/// Accepts a request to open a dual-funded channel with a contribution provided after an
/// [`Event::OpenChannelRequest`].
///
/// The [`Event::OpenChannelRequest::channel_negotiation_type`] field will indicate the open channel
/// request is for a dual-funded channel when the variant is [`InboundChannelFunds::DualFunded`].
///
/// The `temporary_channel_id` parameter indicates which inbound channel should be accepted,
/// and the `counterparty_node_id` parameter is the id of the peer that 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_channel_*` call.
///
/// The `funding_inputs` parameter provides which UTXOs to use for `our_funding_contribution`
/// along with the corresponding satisfaction weight. They must be able to cover any fees needed
/// to pay for the contributed weight to the funding transaction. This includes the witnesses
/// provided through calling [`ChannelManager::funding_transaction_signed`] after receiving
/// [`Event::FundingTransactionReadyForSigning`].
///
/// 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://diyhpl.us/~bryan/irc/bitcoin/bitcoin-dev/linuxfoundation-pipermail/lightning-dev/2023-May/003922.txt
///
/// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
/// [`Event::OpenChannelRequest::channel_negotiation_type`]: events::Event::OpenChannelRequest::channel_negotiation_type
/// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
/// [`Event::FundingTransactionReadyForSigning`]: events::Event::FundingTransactionReadyForSigning
/// [`ChannelManager::funding_transaction_signed`]: ChannelManager::funding_transaction_signed
pub fn accept_inbound_channel_with_contribution(
&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey,
user_channel_id: u128, config_overrides: Option<ChannelConfigOverrides>,
our_funding_contribution: Amount, funding_inputs: Vec<FundingTxInput>,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're also allowed to include outputs, behaving similar to the mixed mode splice, so maybe it's worth waiting until we figure that out in #4261 so we can adopt it here?

change_script: Option<ScriptBuf>,
) -> Result<(), APIError> {
self.do_accept_inbound_channel(
temporary_channel_id,
counterparty_node_id,
false,
user_channel_id,
config_overrides,
our_funding_contribution,
funding_inputs,
change_script,
)
}

/// TODO(dual_funding): Allow contributions, pass intended amount and inputs
#[rustfmt::skip]
fn do_accept_inbound_channel(
&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, accept_0conf: bool,
user_channel_id: u128, config_overrides: Option<ChannelConfigOverrides>
&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey,
accept_0conf: bool, user_channel_id: u128, config_overrides: Option<ChannelConfigOverrides>,
our_funding_contribution: Amount, funding_inputs: Vec<FundingTxInput>,
change_script: Option<ScriptBuf>,
) -> Result<(), APIError> {
if our_funding_contribution > Amount::MAX_MONEY {
return Err(APIError::APIMisuseError {
err: format!("the funding contribution must be smaller than the total bitcoin supply, it was {}", our_funding_contribution)
});
}

let mut config = self.config.read().unwrap().clone();

Expand DownExpand Up@@ -9911,7 +9972,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
&self.channel_type_features(), &peer_state.latest_features,
&open_channel_msg,
user_channel_id, &config, best_block_height,
&self.logger,
&self.logger, our_funding_contribution, funding_inputs, change_script,
).map_err(|e| {
let channel_id = open_channel_msg.common_fields.temporary_channel_id;
MsgHandleErrInternal::from_chan_no_close(e, channel_id)
Expand DownExpand Up@@ -10055,7 +10116,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/

// Inbound V2 channels with contributed inputs are not considered unfunded.
if let Some(unfunded_chan) = chan.as_unfunded_v2() {
if unfunded_chan.funding_negotiation_context.our_funding_contribution > SignedAmount::ZERO {
if unfunded_chan.our_funding_contribution() > Amount::ZERO {
continue;
}
}
Expand DownExpand Up@@ -10197,7 +10258,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
&self.fee_estimator, &self.entropy_source, &self.signer_provider,
self.get_our_node_id(), *counterparty_node_id, &self.channel_type_features(),
&peer_state.latest_features, msg, user_channel_id,
&self.config.read().unwrap(), best_block_height, &self.logger,
&self.config.read().unwrap(), best_block_height, &self.logger, Amount::ZERO, vec![], None,
).map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.common_fields.temporary_channel_id))?;
let message_send_event = MessageSendEvent::SendAcceptChannelV2 {
node_id: *counterparty_node_id,
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 49 additions & 36 deletions lightning/src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -6314,6 +6314,19 @@ where
}
}

#[cfg(all(test))]
pub fn get_initial_counterparty_commitment_signatures_for_test<L: Deref>(
&mut self, funding: &mut FundingScope, logger: &L,
counterparty_next_commitment_point_override: PublicKey,
) -> Option<(Signature, Vec<Signature>)>
where
SP::Target: SignerProvider,
L::Target: Logger,
{
self.counterparty_next_commitment_point = Some(counterparty_next_commitment_point_override);
self.get_initial_counterparty_commitment_signatures(funding, logger)
}

fn check_funding_meets_minimum_depth(&self, funding: &FundingScope, height: u32) -> bool {
let minimum_depth = self
.minimum_depth(funding)
Expand DownExpand Up@@ -13946,7 +13959,9 @@ where
pub funding: FundingScope,
pub context: ChannelContext<SP>,
pub unfunded_context: UnfundedChannelContext,
pub funding_negotiation_context: FundingNegotiationContext,
funding_tx_locktime: LockTime,
#[allow(unused)] // TODO(dual_funding): Remove once initiating V2 channels is enabled.
pub funding_negotiation_context: Option<FundingNegotiationContext>,
/// The current interactive transaction construction session under negotiation.
pub interactive_tx_constructor: Option<InteractiveTxConstructor>,
}
Expand DownExpand Up@@ -14021,7 +14036,8 @@ where
funding,
context,
unfunded_context,
funding_negotiation_context,
funding_tx_locktime,
funding_negotiation_context: Some(funding_negotiation_context),
interactive_tx_constructor: None,
};
Ok(chan)
Expand DownExpand Up@@ -14096,29 +14112,28 @@ where
},
funding_feerate_sat_per_1000_weight: self.context.feerate_per_kw,
second_per_commitment_point,
locktime: self.funding_negotiation_context.funding_tx_locktime.to_consensus_u32(),
locktime: self.funding_tx_locktime.to_consensus_u32(),
require_confirmed_inputs: None,
}
}

/// Creates a new dual-funded channel from a remote side's request for one.
/// Assumes chain_hash has already been checked and corresponds with what we expect!
/// TODO(dual_funding): Allow contributions, pass intended amount and inputs
#[allow(dead_code)] // TODO(dual_funding): Remove once V2 channels is enabled.
#[rustfmt::skip]
pub fn new_inbound<ES: Deref, F: Deref, L: Deref>(
fee_estimator: &LowerBoundedFeeEstimator<F>, entropy_source: &ES, signer_provider: &SP,
holder_node_id: PublicKey, counterparty_node_id: PublicKey, our_supported_features: &ChannelTypeFeatures,
their_features: &InitFeatures, msg: &msgs::OpenChannelV2,
user_id: u128, config: &UserConfig, current_chain_height: u32, logger: &L,
their_features: &InitFeatures, msg: &msgs::OpenChannelV2, user_id: u128, config: &UserConfig,
current_chain_height: u32, logger: &L, our_funding_contribution: Amount,
our_funding_inputs: Vec<FundingTxInput>, change_script: Option<ScriptBuf>,
) -> Result<Self, ChannelError>
where ES::Target: EntropySource,
F::Target: FeeEstimator,
L::Target: Logger,
{
// TODO(dual_funding): Take these as input once supported
let (our_funding_contribution, our_funding_contribution_sats) = (SignedAmount::ZERO, 0u64);
let our_funding_inputs = Vec::new();
debug_assert!(our_funding_contribution <= Amount::MAX_MONEY);
let our_funding_contribution_sats = our_funding_contribution.to_sat();

let channel_value_satoshis =
our_funding_contribution_sats.saturating_add(msg.common_fields.funding_satoshis);
Expand DownExpand Up@@ -14161,39 +14176,33 @@ where
&funding.get_counterparty_pubkeys().revocation_basepoint);
context.channel_id = channel_id;

let funding_tx_locktime = LockTime::from_consensus(msg.locktime);
let funding_negotiation_context = FundingNegotiationContext {
is_initiator: false,
our_funding_contribution,
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
our_funding_contribution: our_funding_contribution
.to_signed()
.expect("our_funding_contribution should not be greater than Amount::MAX_MONEY"),
funding_tx_locktime,
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
shared_funding_input: None,
our_funding_inputs: our_funding_inputs.clone(),
our_funding_outputs: Vec::new(),
change_script: None,
};
let shared_funding_output = TxOut {
value: Amount::from_sat(funding.get_value_satoshis()),
script_pubkey: funding.get_funding_redeemscript().to_p2wsh(),
change_script,
};

let interactive_tx_constructor = Some(InteractiveTxConstructor::new(
InteractiveTxConstructorArgs {
let mut interactive_tx_constructor = funding_negotiation_context
.into_interactive_tx_constructor(
&context,
&funding,
signer_provider,
entropy_source,
holder_node_id,
counterparty_node_id,
channel_id: context.channel_id,
feerate_sat_per_kw: funding_negotiation_context.funding_feerate_sat_per_1000_weight,
funding_tx_locktime: funding_negotiation_context.funding_tx_locktime,
is_initiator: false,
inputs_to_contribute: our_funding_inputs,
shared_funding_input: None,
shared_funding_output: SharedOwnedOutput::new(shared_funding_output, our_funding_contribution_sats),
outputs_to_contribute: funding_negotiation_context.our_funding_outputs.clone(),
}
).map_err(|err| {
let reason = ClosureReason::ProcessingError { err: err.reason.to_string() };
ChannelError::Close((err.reason.to_string(), reason))
})?);
)
.map_err(|err| {
let reason = ClosureReason::ProcessingError { err: err.reason.to_string() };
ChannelError::Close((err.reason.to_string(), reason))
})?;
debug_assert!(interactive_tx_constructor.take_initiator_first_message().is_none());

let unfunded_context = UnfundedChannelContext {
unfunded_channel_age_ticks: 0,
Expand All@@ -14202,9 +14211,10 @@ where
Ok(Self {
funding,
context,
funding_negotiation_context,
interactive_tx_constructor,
unfunded_context,
funding_tx_locktime,
funding_negotiation_context: None,
interactive_tx_constructor: Some(interactive_tx_constructor),
Comment on lines +14216 to +14217

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would be nice to reuse FundingNegotiation here, but it seems unclear whether the last AwaitingSignatures state can be adapted to the initial dual funding state

})
}

Expand DownExpand Up@@ -14267,8 +14277,7 @@ where
}),
channel_type: Some(self.funding.get_channel_type().clone()),
},
funding_satoshis: self.funding_negotiation_context.our_funding_contribution.to_sat()
as u64,
funding_satoshis: self.our_funding_contribution().to_sat(),
second_per_commitment_point,
require_confirmed_inputs: None,
}
Expand All@@ -14283,6 +14292,10 @@ where
pub fn get_accept_channel_v2_message(&self) -> msgs::AcceptChannelV2 {
self.generate_accept_channel_v2_message()
}

pub fn our_funding_contribution(&self) -> Amount {
Amount::from_sat(self.funding.value_to_self_msat / 1000)
}
}

// Unfunded channel utilities
Expand Down
77 changes: 69 additions & 8 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -30,7 +30,7 @@ use bitcoin::hashes::{Hash, HashEngine, HmacEngine};

use bitcoin::secp256k1::Secp256k1;
use bitcoin::secp256k1::{PublicKey, SecretKey};
use bitcoin::{secp256k1, Sequence, SignedAmount};
use bitcoin::{secp256k1, Amount, ScriptBuf, Sequence};

use crate::blinded_path::message::{
AsyncPaymentsContext, BlindedMessagePath, MessageForwardNode, OffersContext,
Expand DownExpand Up@@ -65,7 +65,7 @@ use crate::ln::channel::{
WithChannelContext,
};
use crate::ln::channel_state::ChannelDetails;
use crate::ln::funding::SpliceContribution;
use crate::ln::funding::{FundingTxInput, SpliceContribution};
use crate::ln::inbound_payment;
use crate::ln::interactivetxs::InteractiveTxMessageSend;
use crate::ln::msgs;
Expand DownExpand Up@@ -9814,6 +9814,9 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
false,
user_channel_id,
config_overrides,
Amount::ZERO,
vec![],
None,
)
}

Expand DownExpand Up@@ -9845,15 +9848,73 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
true,
user_channel_id,
config_overrides,
Amount::ZERO,
vec![],
None,
)
}

/// Accepts a request to open a dual-funded channel with a contribution provided after an
/// [`Event::OpenChannelRequest`].
///
/// The [`Event::OpenChannelRequest::channel_negotiation_type`] field will indicate the open channel
/// request is for a dual-funded channel when the variant is [`InboundChannelFunds::DualFunded`].
///
/// The `temporary_channel_id` parameter indicates which inbound channel should be accepted,
/// and the `counterparty_node_id` parameter is the id of the peer that 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_channel_*` call.
///
/// The `funding_inputs` parameter provides which UTXOs to use for `our_funding_contribution`
/// along with the corresponding satisfaction weight. They must be able to cover any fees needed
/// to pay for the contributed weight to the funding transaction. This includes the witnesses
/// provided through calling [`ChannelManager::funding_transaction_signed`] after receiving
/// [`Event::FundingTransactionReadyForSigning`].
///
/// 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://diyhpl.us/~bryan/irc/bitcoin/bitcoin-dev/linuxfoundation-pipermail/lightning-dev/2023-May/003922.txt
///
/// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
/// [`Event::OpenChannelRequest::channel_negotiation_type`]: events::Event::OpenChannelRequest::channel_negotiation_type
/// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
/// [`Event::FundingTransactionReadyForSigning`]: events::Event::FundingTransactionReadyForSigning
/// [`ChannelManager::funding_transaction_signed`]: ChannelManager::funding_transaction_signed
pub fn accept_inbound_channel_with_contribution(
&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey,
user_channel_id: u128, config_overrides: Option<ChannelConfigOverrides>,
our_funding_contribution: Amount, funding_inputs: Vec<FundingTxInput>,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're also allowed to include outputs, behaving similar to the mixed mode splice, so maybe it's worth waiting until we figure that out in #4261 so we can adopt it here?

change_script: Option<ScriptBuf>,
) -> Result<(), APIError> {
self.do_accept_inbound_channel(
temporary_channel_id,
counterparty_node_id,
false,
user_channel_id,
config_overrides,
our_funding_contribution,
funding_inputs,
change_script,
)
}

/// TODO(dual_funding): Allow contributions, pass intended amount and inputs
#[rustfmt::skip]
fn do_accept_inbound_channel(
&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, accept_0conf: bool,
user_channel_id: u128, config_overrides: Option<ChannelConfigOverrides>
&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey,
accept_0conf: bool, user_channel_id: u128, config_overrides: Option<ChannelConfigOverrides>,
our_funding_contribution: Amount, funding_inputs: Vec<FundingTxInput>,
change_script: Option<ScriptBuf>,
) -> Result<(), APIError> {
if our_funding_contribution > Amount::MAX_MONEY {
return Err(APIError::APIMisuseError {
err: format!("the funding contribution must be smaller than the total bitcoin supply, it was {}", our_funding_contribution)
});
}

let mut config = self.config.read().unwrap().clone();

Expand DownExpand Up@@ -9911,7 +9972,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
&self.channel_type_features(), &peer_state.latest_features,
&open_channel_msg,
user_channel_id, &config, best_block_height,
&self.logger,
&self.logger, our_funding_contribution, funding_inputs, change_script,
).map_err(|e| {
let channel_id = open_channel_msg.common_fields.temporary_channel_id;
MsgHandleErrInternal::from_chan_no_close(e, channel_id)
Expand DownExpand Up@@ -10055,7 +10116,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/

// Inbound V2 channels with contributed inputs are not considered unfunded.
if let Some(unfunded_chan) = chan.as_unfunded_v2() {
if unfunded_chan.funding_negotiation_context.our_funding_contribution > SignedAmount::ZERO {
if unfunded_chan.our_funding_contribution() > Amount::ZERO {
continue;
}
}
Expand DownExpand Up@@ -10197,7 +10258,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
&self.fee_estimator, &self.entropy_source, &self.signer_provider,
self.get_our_node_id(), *counterparty_node_id, &self.channel_type_features(),
&peer_state.latest_features, msg, user_channel_id,
&self.config.read().unwrap(), best_block_height, &self.logger,
&self.config.read().unwrap(), best_block_height, &self.logger, Amount::ZERO, vec![], None,
).map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.common_fields.temporary_channel_id))?;
let message_send_event = MessageSendEvent::SendAcceptChannelV2 {
node_id: *counterparty_node_id,
Expand Down
Loading