Merged
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
178 changes: 101 additions & 77 deletions lightning/src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,7 +60,8 @@ use crate::ln::funding::{FundingTxInput, SpliceContribution};
use crate::ln::interactivetxs::{
calculate_change_output_value, get_output_weight, AbortReason, HandleTxCompleteValue,
InteractiveTxConstructor, InteractiveTxConstructorArgs, InteractiveTxMessageSend,
InteractiveTxSigningSession, SharedOwnedInput, SharedOwnedOutput, TX_COMMON_FIELDS_WEIGHT,
InteractiveTxSigningSession, NegotiationError, SharedOwnedInput, SharedOwnedOutput,
TX_COMMON_FIELDS_WEIGHT,
};
use crate::ln::msgs;
use crate::ln::msgs::{ClosingSigned, ClosingSignedFeeRange, DecodeError, OnionErrorPacket};
Expand DownExpand Up@@ -1794,20 +1795,22 @@ where

let (interactive_tx_msg_send, negotiation_complete) = match tx_complete_action {
HandleTxCompleteValue::SendTxMessage(interactive_tx_msg_send) => {
(Some(interactive_tx_msg_send), false)
(Some(interactive_tx_msg_send), None)
},
HandleTxCompleteValue::SendTxComplete(
HandleTxCompleteValue::NegotiationComplete(
interactive_tx_msg_send,
negotiation_complete,
) => (Some(interactive_tx_msg_send), negotiation_complete),
HandleTxCompleteValue::NegotiationComplete => (None, true),
funding_outpoint,
) => (interactive_tx_msg_send, Some(funding_outpoint)),
};
if !negotiation_complete {

let funding_outpoint = if let Some(funding_outpoint) = negotiation_complete {
funding_outpoint
} else {
return Ok((interactive_tx_msg_send, None));
}
};

let commitment_signed = self
.funding_tx_constructed(logger)
.funding_tx_constructed(funding_outpoint, logger)
.map_err(|abort_reason| self.fail_interactive_tx_negotiation(abort_reason, logger))?;
Ok((interactive_tx_msg_send, Some(commitment_signed)))
}
Expand DownExpand Up@@ -1890,13 +1893,13 @@ where
}

fn funding_tx_constructed<L: Deref>(
&mut self, logger: &L,
&mut self, funding_outpoint: OutPoint, logger: &L,
) -> Result<msgs::CommitmentSigned, AbortReason>
where
L::Target: Logger,
{
let logger = WithChannelContext::from(logger, self.context(), None);
match &mut self.phase {
let (interactive_tx_constructor, commitment_signed) = match &mut self.phase {
ChannelPhase::UnfundedV2(chan) => {
debug_assert_eq!(
chan.context.channel_state,
Expand All@@ -1906,60 +1909,85 @@ where
),
);

let signing_session = chan
let interactive_tx_constructor = chan
.interactive_tx_constructor
.take()
.expect("PendingV2Channel::interactive_tx_constructor should be set")
.into_signing_session();
.expect("PendingV2Channel::interactive_tx_constructor should be set");
let commitment_signed = chan.context.funding_tx_constructed(
&mut chan.funding,
signing_session,
funding_outpoint,
false,
chan.unfunded_context.transaction_number(),
&&logger,
)?;

return Ok(commitment_signed);
(interactive_tx_constructor, commitment_signed)
},
ChannelPhase::Funded(chan) => {
if let Some(pending_splice) = chan.pending_splice.as_mut() {
if let Some(funding_negotiation) = pending_splice.funding_negotiation.take() {
if let FundingNegotiation::ConstructingTransaction {
mut funding,
interactive_tx_constructor,
} = funding_negotiation
{
let signing_session = interactive_tx_constructor.into_signing_session();
let commitment_signed = chan.context.funding_tx_constructed(
pending_splice
.funding_negotiation
.take()
.and_then(|funding_negotiation| {
if let FundingNegotiation::ConstructingTransaction {
funding,
interactive_tx_constructor,
} = funding_negotiation
{
Some((funding, interactive_tx_constructor))
} else {
// Replace the taken state for later error handling
pending_splice.funding_negotiation = Some(funding_negotiation);
None
}
})
.ok_or_else(|| {
AbortReason::InternalError(
"Got a tx_complete message in an invalid state",
)
})
.and_then(|(mut funding, interactive_tx_constructor)| {
match chan.context.funding_tx_constructed(
&mut funding,
signing_session,
funding_outpoint,
true,
chan.holder_commitment_point.next_transaction_number(),
&&logger,
)?;

pending_splice.funding_negotiation =
Some(FundingNegotiation::AwaitingSignatures { funding });

return Ok(commitment_signed);
} else {
// Replace the taken state
pending_splice.funding_negotiation = Some(funding_negotiation);
}
}
) {
Ok(commitment_signed) => {
// Advance the state
pending_splice.funding_negotiation =
Some(FundingNegotiation::AwaitingSignatures { funding });
Ok((interactive_tx_constructor, commitment_signed))
},
Err(e) => {
// Restore the taken state for later error handling
pending_splice.funding_negotiation =
Some(FundingNegotiation::ConstructingTransaction {
funding,
interactive_tx_constructor,
});
Err(e)
},
}
})?
} else {
return Err(AbortReason::InternalError(
"Got a tx_complete message in an invalid state",
));
}

return Err(AbortReason::InternalError(
"Got a tx_complete message in an invalid state",
));
},
_ => {
debug_assert!(false);
return Err(AbortReason::InternalError(
"Got a tx_complete message in an invalid phase",
));
},
}
};

let signing_session = interactive_tx_constructor.into_signing_session();
self.context_mut().interactive_tx_signing_session = Some(signing_session);
Ok(commitment_signed)
}

pub fn force_shutdown(&mut self, closure_reason: ClosureReason) -> ShutdownResult {
Expand DownExpand Up@@ -6051,30 +6079,13 @@ where

#[rustfmt::skip]
fn funding_tx_constructed<L: Deref>(
&mut self, funding: &mut FundingScope, signing_session: InteractiveTxSigningSession,
is_splice: bool, holder_commitment_transaction_number: u64, logger: &L
&mut self, funding: &mut FundingScope, funding_outpoint: OutPoint, is_splice: bool,
holder_commitment_transaction_number: u64, logger: &L,
) -> Result<msgs::CommitmentSigned, AbortReason>
where
L::Target: Logger
{
let mut output_index = None;
let expected_spk = funding.get_funding_redeemscript().to_p2wsh();
for (idx, outp) in signing_session.unsigned_tx().tx().output.iter().enumerate() {
if outp.script_pubkey == expected_spk && outp.value.to_sat() == funding.get_value_satoshis() {
if output_index.is_some() {
return Err(AbortReason::DuplicateFundingOutput);
}
output_index = Some(idx as u16);
}
}
let outpoint = if let Some(output_index) = output_index {
OutPoint { txid: signing_session.unsigned_tx().compute_txid(), index: output_index }
} else {
return Err(AbortReason::MissingFundingOutput);
};
funding
.channel_transaction_parameters.funding_outpoint = Some(outpoint);
self.interactive_tx_signing_session = Some(signing_session);
funding.channel_transaction_parameters.funding_outpoint = Some(funding_outpoint);

if is_splice {
debug_assert_eq!(
Expand All@@ -6091,7 +6102,6 @@ where
Some(commitment_signed) => commitment_signed,
// TODO(splicing): Support async signing
None => {
funding.channel_transaction_parameters.funding_outpoint = None;
return Err(AbortReason::InternalError("Failed to compute commitment_signed signatures"));
},
};
Expand DownExpand Up@@ -6167,8 +6177,6 @@ where
SP::Target: SignerProvider,
L::Target: Logger,
{
debug_assert!(self.interactive_tx_signing_session.is_some());

let signatures = self.get_initial_counterparty_commitment_signatures(funding, logger);
if let Some((signature, htlc_signatures)) = signatures {
log_info!(
Expand DownExpand Up@@ -6508,9 +6516,9 @@ impl FundingNegotiationContext {
/// Prepare and start interactive transaction negotiation.
/// If error occurs, it is caused by our side, not the counterparty.
fn into_interactive_tx_constructor<SP: Deref, ES: Deref>(
self, context: &ChannelContext<SP>, funding: &FundingScope, signer_provider: &SP,
mut self, context: &ChannelContext<SP>, funding: &FundingScope, signer_provider: &SP,
entropy_source: &ES, holder_node_id: PublicKey,
) -> Result<InteractiveTxConstructor, AbortReason>
) -> Result<InteractiveTxConstructor, NegotiationError>
where
SP::Target: SignerProvider,
ES::Target: EntropySource,
Expand All@@ -6536,25 +6544,32 @@ impl FundingNegotiationContext {

// Optionally add change output
let change_value_opt = if self.our_funding_contribution > SignedAmount::ZERO {
calculate_change_output_value(
match calculate_change_output_value(
&self,
self.shared_funding_input.is_some(),
&shared_funding_output.script_pubkey,
context.holder_dust_limit_satoshis,
)?
) {
Ok(change_value_opt) => change_value_opt,
Err(reason) => {
return Err(self.into_negotiation_error(reason));
},
}
} else {
None
};

let mut funding_outputs = self.our_funding_outputs;

if let Some(change_value) = change_value_opt {
let change_script = if let Some(script) = self.change_script {
script
} else {
signer_provider
.get_destination_script(context.channel_keys_id)
.map_err(|_err| AbortReason::InternalError("Error getting change script"))?
match signer_provider.get_destination_script(context.channel_keys_id) {
Ok(script) => script,
Err(_) => {
let reason = AbortReason::InternalError("Error getting change script");
return Err(self.into_negotiation_error(reason));
},
}
};
let mut change_output =
TxOut { value: Amount::from_sat(change_value), script_pubkey: change_script };
Expand All@@ -6565,7 +6580,7 @@ impl FundingNegotiationContext {
// Check dust limit again
if change_value_decreased_with_fee > context.holder_dust_limit_satoshis {
change_output.value = Amount::from_sat(change_value_decreased_with_fee);
funding_outputs.push(change_output);
self.our_funding_outputs.push(change_output);
}
}

Expand All@@ -6583,10 +6598,19 @@ impl FundingNegotiationContext {
shared_funding_output,
funding.value_to_self_msat / 1000,
),
outputs_to_contribute: funding_outputs,
outputs_to_contribute: self.our_funding_outputs,
};
InteractiveTxConstructor::new(constructor_args)
}

fn into_negotiation_error(self, reason: AbortReason) -> NegotiationError {
let contributed_inputs =
self.our_funding_inputs.into_iter().map(|input| input.utxo.outpoint).collect();

let contributed_outputs = self.our_funding_outputs;

NegotiationError { reason, contributed_inputs, contributed_outputs }
}
}

// Holder designates channel data owned for the benefit of the user client.
Expand DownExpand Up@@ -13660,8 +13684,8 @@ where
outputs_to_contribute: funding_negotiation_context.our_funding_outputs.clone(),
}
).map_err(|err| {
let reason = ClosureReason::ProcessingError { err: err.to_string() };
ChannelError::Close((err.to_string(), reason))
let reason = ClosureReason::ProcessingError { err: err.reason.to_string() };
ChannelError::Close((err.reason.to_string(), reason))
})?);

let unfunded_context = UnfundedChannelContext {
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
Merged
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
178 changes: 101 additions & 77 deletions lightning/src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,7 +60,8 @@ use crate::ln::funding::{FundingTxInput, SpliceContribution};
use crate::ln::interactivetxs::{
calculate_change_output_value, get_output_weight, AbortReason, HandleTxCompleteValue,
InteractiveTxConstructor, InteractiveTxConstructorArgs, InteractiveTxMessageSend,
InteractiveTxSigningSession, SharedOwnedInput, SharedOwnedOutput, TX_COMMON_FIELDS_WEIGHT,
InteractiveTxSigningSession, NegotiationError, SharedOwnedInput, SharedOwnedOutput,
TX_COMMON_FIELDS_WEIGHT,
};
use crate::ln::msgs;
use crate::ln::msgs::{ClosingSigned, ClosingSignedFeeRange, DecodeError, OnionErrorPacket};
Expand DownExpand Up@@ -1794,20 +1795,22 @@ where

let (interactive_tx_msg_send, negotiation_complete) = match tx_complete_action {
HandleTxCompleteValue::SendTxMessage(interactive_tx_msg_send) => {
(Some(interactive_tx_msg_send), false)
(Some(interactive_tx_msg_send), None)
},
HandleTxCompleteValue::SendTxComplete(
HandleTxCompleteValue::NegotiationComplete(
interactive_tx_msg_send,
negotiation_complete,
) => (Some(interactive_tx_msg_send), negotiation_complete),
HandleTxCompleteValue::NegotiationComplete => (None, true),
funding_outpoint,
) => (interactive_tx_msg_send, Some(funding_outpoint)),
};
if !negotiation_complete {

let funding_outpoint = if let Some(funding_outpoint) = negotiation_complete {
funding_outpoint
} else {
return Ok((interactive_tx_msg_send, None));
}
};

let commitment_signed = self
.funding_tx_constructed(logger)
.funding_tx_constructed(funding_outpoint, logger)
.map_err(|abort_reason| self.fail_interactive_tx_negotiation(abort_reason, logger))?;
Ok((interactive_tx_msg_send, Some(commitment_signed)))
}
Expand DownExpand Up@@ -1890,13 +1893,13 @@ where
}

fn funding_tx_constructed<L: Deref>(
&mut self, logger: &L,
&mut self, funding_outpoint: OutPoint, logger: &L,
) -> Result<msgs::CommitmentSigned, AbortReason>
where
L::Target: Logger,
{
let logger = WithChannelContext::from(logger, self.context(), None);
match &mut self.phase {
let (interactive_tx_constructor, commitment_signed) = match &mut self.phase {
ChannelPhase::UnfundedV2(chan) => {
debug_assert_eq!(
chan.context.channel_state,
Expand All@@ -1906,60 +1909,85 @@ where
),
);

let signing_session = chan
let interactive_tx_constructor = chan
.interactive_tx_constructor
.take()
.expect("PendingV2Channel::interactive_tx_constructor should be set")
.into_signing_session();
.expect("PendingV2Channel::interactive_tx_constructor should be set");
let commitment_signed = chan.context.funding_tx_constructed(
&mut chan.funding,
signing_session,
funding_outpoint,
false,
chan.unfunded_context.transaction_number(),
&&logger,
)?;

return Ok(commitment_signed);
(interactive_tx_constructor, commitment_signed)
},
ChannelPhase::Funded(chan) => {
if let Some(pending_splice) = chan.pending_splice.as_mut() {
if let Some(funding_negotiation) = pending_splice.funding_negotiation.take() {
if let FundingNegotiation::ConstructingTransaction {
mut funding,
interactive_tx_constructor,
} = funding_negotiation
{
let signing_session = interactive_tx_constructor.into_signing_session();
let commitment_signed = chan.context.funding_tx_constructed(
pending_splice
.funding_negotiation
.take()
.and_then(|funding_negotiation| {
if let FundingNegotiation::ConstructingTransaction {
funding,
interactive_tx_constructor,
} = funding_negotiation
{
Some((funding, interactive_tx_constructor))
} else {
// Replace the taken state for later error handling
pending_splice.funding_negotiation = Some(funding_negotiation);
None
}
})
.ok_or_else(|| {
AbortReason::InternalError(
"Got a tx_complete message in an invalid state",
)
})
.and_then(|(mut funding, interactive_tx_constructor)| {
match chan.context.funding_tx_constructed(
&mut funding,
signing_session,
funding_outpoint,
true,
chan.holder_commitment_point.next_transaction_number(),
&&logger,
)?;

pending_splice.funding_negotiation =
Some(FundingNegotiation::AwaitingSignatures { funding });

return Ok(commitment_signed);
} else {
// Replace the taken state
pending_splice.funding_negotiation = Some(funding_negotiation);
}
}
) {
Ok(commitment_signed) => {
// Advance the state
pending_splice.funding_negotiation =
Some(FundingNegotiation::AwaitingSignatures { funding });
Ok((interactive_tx_constructor, commitment_signed))
},
Err(e) => {
// Restore the taken state for later error handling
pending_splice.funding_negotiation =
Some(FundingNegotiation::ConstructingTransaction {
funding,
interactive_tx_constructor,
});
Err(e)
},
}
})?
} else {
return Err(AbortReason::InternalError(
"Got a tx_complete message in an invalid state",
));
}

return Err(AbortReason::InternalError(
"Got a tx_complete message in an invalid state",
));
},
_ => {
debug_assert!(false);
return Err(AbortReason::InternalError(
"Got a tx_complete message in an invalid phase",
));
},
}
};

let signing_session = interactive_tx_constructor.into_signing_session();
self.context_mut().interactive_tx_signing_session = Some(signing_session);
Ok(commitment_signed)
}

pub fn force_shutdown(&mut self, closure_reason: ClosureReason) -> ShutdownResult {
Expand DownExpand Up@@ -6051,30 +6079,13 @@ where

#[rustfmt::skip]
fn funding_tx_constructed<L: Deref>(
&mut self, funding: &mut FundingScope, signing_session: InteractiveTxSigningSession,
is_splice: bool, holder_commitment_transaction_number: u64, logger: &L
&mut self, funding: &mut FundingScope, funding_outpoint: OutPoint, is_splice: bool,
holder_commitment_transaction_number: u64, logger: &L,
) -> Result<msgs::CommitmentSigned, AbortReason>
where
L::Target: Logger
{
let mut output_index = None;
let expected_spk = funding.get_funding_redeemscript().to_p2wsh();
for (idx, outp) in signing_session.unsigned_tx().tx().output.iter().enumerate() {
if outp.script_pubkey == expected_spk && outp.value.to_sat() == funding.get_value_satoshis() {
if output_index.is_some() {
return Err(AbortReason::DuplicateFundingOutput);
}
output_index = Some(idx as u16);
}
}
let outpoint = if let Some(output_index) = output_index {
OutPoint { txid: signing_session.unsigned_tx().compute_txid(), index: output_index }
} else {
return Err(AbortReason::MissingFundingOutput);
};
funding
.channel_transaction_parameters.funding_outpoint = Some(outpoint);
self.interactive_tx_signing_session = Some(signing_session);
funding.channel_transaction_parameters.funding_outpoint = Some(funding_outpoint);

if is_splice {
debug_assert_eq!(
Expand All@@ -6091,7 +6102,6 @@ where
Some(commitment_signed) => commitment_signed,
// TODO(splicing): Support async signing
None => {
funding.channel_transaction_parameters.funding_outpoint = None;
return Err(AbortReason::InternalError("Failed to compute commitment_signed signatures"));
},
};
Expand DownExpand Up@@ -6167,8 +6177,6 @@ where
SP::Target: SignerProvider,
L::Target: Logger,
{
debug_assert!(self.interactive_tx_signing_session.is_some());

let signatures = self.get_initial_counterparty_commitment_signatures(funding, logger);
if let Some((signature, htlc_signatures)) = signatures {
log_info!(
Expand DownExpand Up@@ -6508,9 +6516,9 @@ impl FundingNegotiationContext {
/// Prepare and start interactive transaction negotiation.
/// If error occurs, it is caused by our side, not the counterparty.
fn into_interactive_tx_constructor<SP: Deref, ES: Deref>(
self, context: &ChannelContext<SP>, funding: &FundingScope, signer_provider: &SP,
mut self, context: &ChannelContext<SP>, funding: &FundingScope, signer_provider: &SP,
entropy_source: &ES, holder_node_id: PublicKey,
) -> Result<InteractiveTxConstructor, AbortReason>
) -> Result<InteractiveTxConstructor, NegotiationError>
where
SP::Target: SignerProvider,
ES::Target: EntropySource,
Expand All@@ -6536,25 +6544,32 @@ impl FundingNegotiationContext {

// Optionally add change output
let change_value_opt = if self.our_funding_contribution > SignedAmount::ZERO {
calculate_change_output_value(
match calculate_change_output_value(
&self,
self.shared_funding_input.is_some(),
&shared_funding_output.script_pubkey,
context.holder_dust_limit_satoshis,
)?
) {
Ok(change_value_opt) => change_value_opt,
Err(reason) => {
return Err(self.into_negotiation_error(reason));
},
}
} else {
None
};

let mut funding_outputs = self.our_funding_outputs;

if let Some(change_value) = change_value_opt {
let change_script = if let Some(script) = self.change_script {
script
} else {
signer_provider
.get_destination_script(context.channel_keys_id)
.map_err(|_err| AbortReason::InternalError("Error getting change script"))?
match signer_provider.get_destination_script(context.channel_keys_id) {
Ok(script) => script,
Err(_) => {
let reason = AbortReason::InternalError("Error getting change script");
return Err(self.into_negotiation_error(reason));
},
}
};
let mut change_output =
TxOut { value: Amount::from_sat(change_value), script_pubkey: change_script };
Expand All@@ -6565,7 +6580,7 @@ impl FundingNegotiationContext {
// Check dust limit again
if change_value_decreased_with_fee > context.holder_dust_limit_satoshis {
change_output.value = Amount::from_sat(change_value_decreased_with_fee);
funding_outputs.push(change_output);
self.our_funding_outputs.push(change_output);
}
}

Expand All@@ -6583,10 +6598,19 @@ impl FundingNegotiationContext {
shared_funding_output,
funding.value_to_self_msat / 1000,
),
outputs_to_contribute: funding_outputs,
outputs_to_contribute: self.our_funding_outputs,
};
InteractiveTxConstructor::new(constructor_args)
}

fn into_negotiation_error(self, reason: AbortReason) -> NegotiationError {
let contributed_inputs =
self.our_funding_inputs.into_iter().map(|input| input.utxo.outpoint).collect();

let contributed_outputs = self.our_funding_outputs;

NegotiationError { reason, contributed_inputs, contributed_outputs }
}
}

// Holder designates channel data owned for the benefit of the user client.
Expand DownExpand Up@@ -13660,8 +13684,8 @@ where
outputs_to_contribute: funding_negotiation_context.our_funding_outputs.clone(),
}
).map_err(|err| {
let reason = ClosureReason::ProcessingError { err: err.to_string() };
ChannelError::Close((err.to_string(), reason))
let reason = ClosureReason::ProcessingError { err: err.reason.to_string() };
ChannelError::Close((err.reason.to_string(), reason))
})?);

let unfunded_context = UnfundedChannelContext {
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
Merged
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
178 changes: 101 additions & 77 deletions lightning/src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,7 +60,8 @@ use crate::ln::funding::{FundingTxInput, SpliceContribution};
use crate::ln::interactivetxs::{
calculate_change_output_value, get_output_weight, AbortReason, HandleTxCompleteValue,
InteractiveTxConstructor, InteractiveTxConstructorArgs, InteractiveTxMessageSend,
InteractiveTxSigningSession, SharedOwnedInput, SharedOwnedOutput, TX_COMMON_FIELDS_WEIGHT,
InteractiveTxSigningSession, NegotiationError, SharedOwnedInput, SharedOwnedOutput,
TX_COMMON_FIELDS_WEIGHT,
};
use crate::ln::msgs;
use crate::ln::msgs::{ClosingSigned, ClosingSignedFeeRange, DecodeError, OnionErrorPacket};
Expand DownExpand Up@@ -1794,20 +1795,22 @@ where

let (interactive_tx_msg_send, negotiation_complete) = match tx_complete_action {
HandleTxCompleteValue::SendTxMessage(interactive_tx_msg_send) => {
(Some(interactive_tx_msg_send), false)
(Some(interactive_tx_msg_send), None)
},
HandleTxCompleteValue::SendTxComplete(
HandleTxCompleteValue::NegotiationComplete(
interactive_tx_msg_send,
negotiation_complete,
) => (Some(interactive_tx_msg_send), negotiation_complete),
HandleTxCompleteValue::NegotiationComplete => (None, true),
funding_outpoint,
) => (interactive_tx_msg_send, Some(funding_outpoint)),
};
if !negotiation_complete {

let funding_outpoint = if let Some(funding_outpoint) = negotiation_complete {
funding_outpoint
} else {
return Ok((interactive_tx_msg_send, None));
}
};

let commitment_signed = self
.funding_tx_constructed(logger)
.funding_tx_constructed(funding_outpoint, logger)
.map_err(|abort_reason| self.fail_interactive_tx_negotiation(abort_reason, logger))?;
Ok((interactive_tx_msg_send, Some(commitment_signed)))
}
Expand DownExpand Up@@ -1890,13 +1893,13 @@ where
}

fn funding_tx_constructed<L: Deref>(
&mut self, logger: &L,
&mut self, funding_outpoint: OutPoint, logger: &L,
) -> Result<msgs::CommitmentSigned, AbortReason>
where
L::Target: Logger,
{
let logger = WithChannelContext::from(logger, self.context(), None);
match &mut self.phase {
let (interactive_tx_constructor, commitment_signed) = match &mut self.phase {
ChannelPhase::UnfundedV2(chan) => {
debug_assert_eq!(
chan.context.channel_state,
Expand All@@ -1906,60 +1909,85 @@ where
),
);

let signing_session = chan
let interactive_tx_constructor = chan
.interactive_tx_constructor
.take()
.expect("PendingV2Channel::interactive_tx_constructor should be set")
.into_signing_session();
.expect("PendingV2Channel::interactive_tx_constructor should be set");
let commitment_signed = chan.context.funding_tx_constructed(
&mut chan.funding,
signing_session,
funding_outpoint,
false,
chan.unfunded_context.transaction_number(),
&&logger,
)?;

return Ok(commitment_signed);
(interactive_tx_constructor, commitment_signed)
},
ChannelPhase::Funded(chan) => {
if let Some(pending_splice) = chan.pending_splice.as_mut() {
if let Some(funding_negotiation) = pending_splice.funding_negotiation.take() {
if let FundingNegotiation::ConstructingTransaction {
mut funding,
interactive_tx_constructor,
} = funding_negotiation
{
let signing_session = interactive_tx_constructor.into_signing_session();
let commitment_signed = chan.context.funding_tx_constructed(
pending_splice
.funding_negotiation
.take()
.and_then(|funding_negotiation| {
if let FundingNegotiation::ConstructingTransaction {
funding,
interactive_tx_constructor,
} = funding_negotiation
{
Some((funding, interactive_tx_constructor))
} else {
// Replace the taken state for later error handling
pending_splice.funding_negotiation = Some(funding_negotiation);
None
}
})
.ok_or_else(|| {
AbortReason::InternalError(
"Got a tx_complete message in an invalid state",
)
})
.and_then(|(mut funding, interactive_tx_constructor)| {
match chan.context.funding_tx_constructed(
&mut funding,
signing_session,
funding_outpoint,
true,
chan.holder_commitment_point.next_transaction_number(),
&&logger,
)?;

pending_splice.funding_negotiation =
Some(FundingNegotiation::AwaitingSignatures { funding });

return Ok(commitment_signed);
} else {
// Replace the taken state
pending_splice.funding_negotiation = Some(funding_negotiation);
}
}
) {
Ok(commitment_signed) => {
// Advance the state
pending_splice.funding_negotiation =
Some(FundingNegotiation::AwaitingSignatures { funding });
Ok((interactive_tx_constructor, commitment_signed))
},
Err(e) => {
// Restore the taken state for later error handling
pending_splice.funding_negotiation =
Some(FundingNegotiation::ConstructingTransaction {
funding,
interactive_tx_constructor,
});
Err(e)
},
}
})?
} else {
return Err(AbortReason::InternalError(
"Got a tx_complete message in an invalid state",
));
}

return Err(AbortReason::InternalError(
"Got a tx_complete message in an invalid state",
));
},
_ => {
debug_assert!(false);
return Err(AbortReason::InternalError(
"Got a tx_complete message in an invalid phase",
));
},
}
};

let signing_session = interactive_tx_constructor.into_signing_session();
self.context_mut().interactive_tx_signing_session = Some(signing_session);
Ok(commitment_signed)
}

pub fn force_shutdown(&mut self, closure_reason: ClosureReason) -> ShutdownResult {
Expand DownExpand Up@@ -6051,30 +6079,13 @@ where

#[rustfmt::skip]
fn funding_tx_constructed<L: Deref>(
&mut self, funding: &mut FundingScope, signing_session: InteractiveTxSigningSession,
is_splice: bool, holder_commitment_transaction_number: u64, logger: &L
&mut self, funding: &mut FundingScope, funding_outpoint: OutPoint, is_splice: bool,
holder_commitment_transaction_number: u64, logger: &L,
) -> Result<msgs::CommitmentSigned, AbortReason>
where
L::Target: Logger
{
let mut output_index = None;
let expected_spk = funding.get_funding_redeemscript().to_p2wsh();
for (idx, outp) in signing_session.unsigned_tx().tx().output.iter().enumerate() {
if outp.script_pubkey == expected_spk && outp.value.to_sat() == funding.get_value_satoshis() {
if output_index.is_some() {
return Err(AbortReason::DuplicateFundingOutput);
}
output_index = Some(idx as u16);
}
}
let outpoint = if let Some(output_index) = output_index {
OutPoint { txid: signing_session.unsigned_tx().compute_txid(), index: output_index }
} else {
return Err(AbortReason::MissingFundingOutput);
};
funding
.channel_transaction_parameters.funding_outpoint = Some(outpoint);
self.interactive_tx_signing_session = Some(signing_session);
funding.channel_transaction_parameters.funding_outpoint = Some(funding_outpoint);

if is_splice {
debug_assert_eq!(
Expand All@@ -6091,7 +6102,6 @@ where
Some(commitment_signed) => commitment_signed,
// TODO(splicing): Support async signing
None => {
funding.channel_transaction_parameters.funding_outpoint = None;
return Err(AbortReason::InternalError("Failed to compute commitment_signed signatures"));
},
};
Expand DownExpand Up@@ -6167,8 +6177,6 @@ where
SP::Target: SignerProvider,
L::Target: Logger,
{
debug_assert!(self.interactive_tx_signing_session.is_some());

let signatures = self.get_initial_counterparty_commitment_signatures(funding, logger);
if let Some((signature, htlc_signatures)) = signatures {
log_info!(
Expand DownExpand Up@@ -6508,9 +6516,9 @@ impl FundingNegotiationContext {
/// Prepare and start interactive transaction negotiation.
/// If error occurs, it is caused by our side, not the counterparty.
fn into_interactive_tx_constructor<SP: Deref, ES: Deref>(
self, context: &ChannelContext<SP>, funding: &FundingScope, signer_provider: &SP,
mut self, context: &ChannelContext<SP>, funding: &FundingScope, signer_provider: &SP,
entropy_source: &ES, holder_node_id: PublicKey,
) -> Result<InteractiveTxConstructor, AbortReason>
) -> Result<InteractiveTxConstructor, NegotiationError>
where
SP::Target: SignerProvider,
ES::Target: EntropySource,
Expand All@@ -6536,25 +6544,32 @@ impl FundingNegotiationContext {

// Optionally add change output
let change_value_opt = if self.our_funding_contribution > SignedAmount::ZERO {
calculate_change_output_value(
match calculate_change_output_value(
&self,
self.shared_funding_input.is_some(),
&shared_funding_output.script_pubkey,
context.holder_dust_limit_satoshis,
)?
) {
Ok(change_value_opt) => change_value_opt,
Err(reason) => {
return Err(self.into_negotiation_error(reason));
},
}
} else {
None
};

let mut funding_outputs = self.our_funding_outputs;

if let Some(change_value) = change_value_opt {
let change_script = if let Some(script) = self.change_script {
script
} else {
signer_provider
.get_destination_script(context.channel_keys_id)
.map_err(|_err| AbortReason::InternalError("Error getting change script"))?
match signer_provider.get_destination_script(context.channel_keys_id) {
Ok(script) => script,
Err(_) => {
let reason = AbortReason::InternalError("Error getting change script");
return Err(self.into_negotiation_error(reason));
},
}
};
let mut change_output =
TxOut { value: Amount::from_sat(change_value), script_pubkey: change_script };
Expand All@@ -6565,7 +6580,7 @@ impl FundingNegotiationContext {
// Check dust limit again
if change_value_decreased_with_fee > context.holder_dust_limit_satoshis {
change_output.value = Amount::from_sat(change_value_decreased_with_fee);
funding_outputs.push(change_output);
self.our_funding_outputs.push(change_output);
}
}

Expand All@@ -6583,10 +6598,19 @@ impl FundingNegotiationContext {
shared_funding_output,
funding.value_to_self_msat / 1000,
),
outputs_to_contribute: funding_outputs,
outputs_to_contribute: self.our_funding_outputs,
};
InteractiveTxConstructor::new(constructor_args)
}

fn into_negotiation_error(self, reason: AbortReason) -> NegotiationError {
let contributed_inputs =
self.our_funding_inputs.into_iter().map(|input| input.utxo.outpoint).collect();

let contributed_outputs = self.our_funding_outputs;

NegotiationError { reason, contributed_inputs, contributed_outputs }
}
}

// Holder designates channel data owned for the benefit of the user client.
Expand DownExpand Up@@ -13660,8 +13684,8 @@ where
outputs_to_contribute: funding_negotiation_context.our_funding_outputs.clone(),
}
).map_err(|err| {
let reason = ClosureReason::ProcessingError { err: err.to_string() };
ChannelError::Close((err.to_string(), reason))
let reason = ClosureReason::ProcessingError { err: err.reason.to_string() };
ChannelError::Close((err.reason.to_string(), reason))
})?);

let unfunded_context = UnfundedChannelContext {
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
Merged
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
178 changes: 101 additions & 77 deletions lightning/src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,7 +60,8 @@ use crate::ln::funding::{FundingTxInput, SpliceContribution};
use crate::ln::interactivetxs::{
calculate_change_output_value, get_output_weight, AbortReason, HandleTxCompleteValue,
InteractiveTxConstructor, InteractiveTxConstructorArgs, InteractiveTxMessageSend,
InteractiveTxSigningSession, SharedOwnedInput, SharedOwnedOutput, TX_COMMON_FIELDS_WEIGHT,
InteractiveTxSigningSession, NegotiationError, SharedOwnedInput, SharedOwnedOutput,
TX_COMMON_FIELDS_WEIGHT,
};
use crate::ln::msgs;
use crate::ln::msgs::{ClosingSigned, ClosingSignedFeeRange, DecodeError, OnionErrorPacket};
Expand DownExpand Up@@ -1794,20 +1795,22 @@ where

let (interactive_tx_msg_send, negotiation_complete) = match tx_complete_action {
HandleTxCompleteValue::SendTxMessage(interactive_tx_msg_send) => {
(Some(interactive_tx_msg_send), false)
(Some(interactive_tx_msg_send), None)
},
HandleTxCompleteValue::SendTxComplete(
HandleTxCompleteValue::NegotiationComplete(
interactive_tx_msg_send,
negotiation_complete,
) => (Some(interactive_tx_msg_send), negotiation_complete),
HandleTxCompleteValue::NegotiationComplete => (None, true),
funding_outpoint,
) => (interactive_tx_msg_send, Some(funding_outpoint)),
};
if !negotiation_complete {

let funding_outpoint = if let Some(funding_outpoint) = negotiation_complete {
funding_outpoint
} else {
return Ok((interactive_tx_msg_send, None));
}
};

let commitment_signed = self
.funding_tx_constructed(logger)
.funding_tx_constructed(funding_outpoint, logger)
.map_err(|abort_reason| self.fail_interactive_tx_negotiation(abort_reason, logger))?;
Ok((interactive_tx_msg_send, Some(commitment_signed)))
}
Expand DownExpand Up@@ -1890,13 +1893,13 @@ where
}

fn funding_tx_constructed<L: Deref>(
&mut self, logger: &L,
&mut self, funding_outpoint: OutPoint, logger: &L,
) -> Result<msgs::CommitmentSigned, AbortReason>
where
L::Target: Logger,
{
let logger = WithChannelContext::from(logger, self.context(), None);
match &mut self.phase {
let (interactive_tx_constructor, commitment_signed) = match &mut self.phase {
ChannelPhase::UnfundedV2(chan) => {
debug_assert_eq!(
chan.context.channel_state,
Expand All@@ -1906,60 +1909,85 @@ where
),
);

let signing_session = chan
let interactive_tx_constructor = chan
.interactive_tx_constructor
.take()
.expect("PendingV2Channel::interactive_tx_constructor should be set")
.into_signing_session();
.expect("PendingV2Channel::interactive_tx_constructor should be set");
let commitment_signed = chan.context.funding_tx_constructed(
&mut chan.funding,
signing_session,
funding_outpoint,
false,
chan.unfunded_context.transaction_number(),
&&logger,
)?;

return Ok(commitment_signed);
(interactive_tx_constructor, commitment_signed)
},
ChannelPhase::Funded(chan) => {
if let Some(pending_splice) = chan.pending_splice.as_mut() {
if let Some(funding_negotiation) = pending_splice.funding_negotiation.take() {
if let FundingNegotiation::ConstructingTransaction {
mut funding,
interactive_tx_constructor,
} = funding_negotiation
{
let signing_session = interactive_tx_constructor.into_signing_session();
let commitment_signed = chan.context.funding_tx_constructed(
pending_splice
.funding_negotiation
.take()
.and_then(|funding_negotiation| {
if let FundingNegotiation::ConstructingTransaction {
funding,
interactive_tx_constructor,
} = funding_negotiation
{
Some((funding, interactive_tx_constructor))
} else {
// Replace the taken state for later error handling
pending_splice.funding_negotiation = Some(funding_negotiation);
None
}
})
.ok_or_else(|| {
AbortReason::InternalError(
"Got a tx_complete message in an invalid state",
)
})
.and_then(|(mut funding, interactive_tx_constructor)| {
match chan.context.funding_tx_constructed(
&mut funding,
signing_session,
funding_outpoint,
true,
chan.holder_commitment_point.next_transaction_number(),
&&logger,
)?;

pending_splice.funding_negotiation =
Some(FundingNegotiation::AwaitingSignatures { funding });

return Ok(commitment_signed);
} else {
// Replace the taken state
pending_splice.funding_negotiation = Some(funding_negotiation);
}
}
) {
Ok(commitment_signed) => {
// Advance the state
pending_splice.funding_negotiation =
Some(FundingNegotiation::AwaitingSignatures { funding });
Ok((interactive_tx_constructor, commitment_signed))
},
Err(e) => {
// Restore the taken state for later error handling
pending_splice.funding_negotiation =
Some(FundingNegotiation::ConstructingTransaction {
funding,
interactive_tx_constructor,
});
Err(e)
},
}
})?
} else {
return Err(AbortReason::InternalError(
"Got a tx_complete message in an invalid state",
));
}

return Err(AbortReason::InternalError(
"Got a tx_complete message in an invalid state",
));
},
_ => {
debug_assert!(false);
return Err(AbortReason::InternalError(
"Got a tx_complete message in an invalid phase",
));
},
}
};

let signing_session = interactive_tx_constructor.into_signing_session();
self.context_mut().interactive_tx_signing_session = Some(signing_session);
Ok(commitment_signed)
}

pub fn force_shutdown(&mut self, closure_reason: ClosureReason) -> ShutdownResult {
Expand DownExpand Up@@ -6051,30 +6079,13 @@ where

#[rustfmt::skip]
fn funding_tx_constructed<L: Deref>(
&mut self, funding: &mut FundingScope, signing_session: InteractiveTxSigningSession,
is_splice: bool, holder_commitment_transaction_number: u64, logger: &L
&mut self, funding: &mut FundingScope, funding_outpoint: OutPoint, is_splice: bool,
holder_commitment_transaction_number: u64, logger: &L,
) -> Result<msgs::CommitmentSigned, AbortReason>
where
L::Target: Logger
{
let mut output_index = None;
let expected_spk = funding.get_funding_redeemscript().to_p2wsh();
for (idx, outp) in signing_session.unsigned_tx().tx().output.iter().enumerate() {
if outp.script_pubkey == expected_spk && outp.value.to_sat() == funding.get_value_satoshis() {
if output_index.is_some() {
return Err(AbortReason::DuplicateFundingOutput);
}
output_index = Some(idx as u16);
}
}
let outpoint = if let Some(output_index) = output_index {
OutPoint { txid: signing_session.unsigned_tx().compute_txid(), index: output_index }
} else {
return Err(AbortReason::MissingFundingOutput);
};
funding
.channel_transaction_parameters.funding_outpoint = Some(outpoint);
self.interactive_tx_signing_session = Some(signing_session);
funding.channel_transaction_parameters.funding_outpoint = Some(funding_outpoint);

if is_splice {
debug_assert_eq!(
Expand All@@ -6091,7 +6102,6 @@ where
Some(commitment_signed) => commitment_signed,
// TODO(splicing): Support async signing
None => {
funding.channel_transaction_parameters.funding_outpoint = None;
return Err(AbortReason::InternalError("Failed to compute commitment_signed signatures"));
},
};
Expand DownExpand Up@@ -6167,8 +6177,6 @@ where
SP::Target: SignerProvider,
L::Target: Logger,
{
debug_assert!(self.interactive_tx_signing_session.is_some());

let signatures = self.get_initial_counterparty_commitment_signatures(funding, logger);
if let Some((signature, htlc_signatures)) = signatures {
log_info!(
Expand DownExpand Up@@ -6508,9 +6516,9 @@ impl FundingNegotiationContext {
/// Prepare and start interactive transaction negotiation.
/// If error occurs, it is caused by our side, not the counterparty.
fn into_interactive_tx_constructor<SP: Deref, ES: Deref>(
self, context: &ChannelContext<SP>, funding: &FundingScope, signer_provider: &SP,
mut self, context: &ChannelContext<SP>, funding: &FundingScope, signer_provider: &SP,
entropy_source: &ES, holder_node_id: PublicKey,
) -> Result<InteractiveTxConstructor, AbortReason>
) -> Result<InteractiveTxConstructor, NegotiationError>
where
SP::Target: SignerProvider,
ES::Target: EntropySource,
Expand All@@ -6536,25 +6544,32 @@ impl FundingNegotiationContext {

// Optionally add change output
let change_value_opt = if self.our_funding_contribution > SignedAmount::ZERO {
calculate_change_output_value(
match calculate_change_output_value(
&self,
self.shared_funding_input.is_some(),
&shared_funding_output.script_pubkey,
context.holder_dust_limit_satoshis,
)?
) {
Ok(change_value_opt) => change_value_opt,
Err(reason) => {
return Err(self.into_negotiation_error(reason));
},
}
} else {
None
};

let mut funding_outputs = self.our_funding_outputs;

if let Some(change_value) = change_value_opt {
let change_script = if let Some(script) = self.change_script {
script
} else {
signer_provider
.get_destination_script(context.channel_keys_id)
.map_err(|_err| AbortReason::InternalError("Error getting change script"))?
match signer_provider.get_destination_script(context.channel_keys_id) {
Ok(script) => script,
Err(_) => {
let reason = AbortReason::InternalError("Error getting change script");
return Err(self.into_negotiation_error(reason));
},
}
};
let mut change_output =
TxOut { value: Amount::from_sat(change_value), script_pubkey: change_script };
Expand All@@ -6565,7 +6580,7 @@ impl FundingNegotiationContext {
// Check dust limit again
if change_value_decreased_with_fee > context.holder_dust_limit_satoshis {
change_output.value = Amount::from_sat(change_value_decreased_with_fee);
funding_outputs.push(change_output);
self.our_funding_outputs.push(change_output);
}
}

Expand All@@ -6583,10 +6598,19 @@ impl FundingNegotiationContext {
shared_funding_output,
funding.value_to_self_msat / 1000,
),
outputs_to_contribute: funding_outputs,
outputs_to_contribute: self.our_funding_outputs,
};
InteractiveTxConstructor::new(constructor_args)
}

fn into_negotiation_error(self, reason: AbortReason) -> NegotiationError {
let contributed_inputs =
self.our_funding_inputs.into_iter().map(|input| input.utxo.outpoint).collect();

let contributed_outputs = self.our_funding_outputs;

NegotiationError { reason, contributed_inputs, contributed_outputs }
}
}

// Holder designates channel data owned for the benefit of the user client.
Expand DownExpand Up@@ -13660,8 +13684,8 @@ where
outputs_to_contribute: funding_negotiation_context.our_funding_outputs.clone(),
}
).map_err(|err| {
let reason = ClosureReason::ProcessingError { err: err.to_string() };
ChannelError::Close((err.to_string(), reason))
let reason = ClosureReason::ProcessingError { err: err.reason.to_string() };
ChannelError::Close((err.reason.to_string(), reason))
})?);

let unfunded_context = UnfundedChannelContext {
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
Merged
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
178 changes: 101 additions & 77 deletions lightning/src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,7 +60,8 @@ use crate::ln::funding::{FundingTxInput, SpliceContribution};
use crate::ln::interactivetxs::{
calculate_change_output_value, get_output_weight, AbortReason, HandleTxCompleteValue,
InteractiveTxConstructor, InteractiveTxConstructorArgs, InteractiveTxMessageSend,
InteractiveTxSigningSession, SharedOwnedInput, SharedOwnedOutput, TX_COMMON_FIELDS_WEIGHT,
InteractiveTxSigningSession, NegotiationError, SharedOwnedInput, SharedOwnedOutput,
TX_COMMON_FIELDS_WEIGHT,
};
use crate::ln::msgs;
use crate::ln::msgs::{ClosingSigned, ClosingSignedFeeRange, DecodeError, OnionErrorPacket};
Expand DownExpand Up@@ -1794,20 +1795,22 @@ where

let (interactive_tx_msg_send, negotiation_complete) = match tx_complete_action {
HandleTxCompleteValue::SendTxMessage(interactive_tx_msg_send) => {
(Some(interactive_tx_msg_send), false)
(Some(interactive_tx_msg_send), None)
},
HandleTxCompleteValue::SendTxComplete(
HandleTxCompleteValue::NegotiationComplete(
interactive_tx_msg_send,
negotiation_complete,
) => (Some(interactive_tx_msg_send), negotiation_complete),
HandleTxCompleteValue::NegotiationComplete => (None, true),
funding_outpoint,
) => (interactive_tx_msg_send, Some(funding_outpoint)),
};
if !negotiation_complete {

let funding_outpoint = if let Some(funding_outpoint) = negotiation_complete {
funding_outpoint
} else {
return Ok((interactive_tx_msg_send, None));
}
};

let commitment_signed = self
.funding_tx_constructed(logger)
.funding_tx_constructed(funding_outpoint, logger)
.map_err(|abort_reason| self.fail_interactive_tx_negotiation(abort_reason, logger))?;
Ok((interactive_tx_msg_send, Some(commitment_signed)))
}
Expand DownExpand Up@@ -1890,13 +1893,13 @@ where
}

fn funding_tx_constructed<L: Deref>(
&mut self, logger: &L,
&mut self, funding_outpoint: OutPoint, logger: &L,
) -> Result<msgs::CommitmentSigned, AbortReason>
where
L::Target: Logger,
{
let logger = WithChannelContext::from(logger, self.context(), None);
match &mut self.phase {
let (interactive_tx_constructor, commitment_signed) = match &mut self.phase {
ChannelPhase::UnfundedV2(chan) => {
debug_assert_eq!(
chan.context.channel_state,
Expand All@@ -1906,60 +1909,85 @@ where
),
);

let signing_session = chan
let interactive_tx_constructor = chan
.interactive_tx_constructor
.take()
.expect("PendingV2Channel::interactive_tx_constructor should be set")
.into_signing_session();
.expect("PendingV2Channel::interactive_tx_constructor should be set");
let commitment_signed = chan.context.funding_tx_constructed(
&mut chan.funding,
signing_session,
funding_outpoint,
false,
chan.unfunded_context.transaction_number(),
&&logger,
)?;

return Ok(commitment_signed);
(interactive_tx_constructor, commitment_signed)
},
ChannelPhase::Funded(chan) => {
if let Some(pending_splice) = chan.pending_splice.as_mut() {
if let Some(funding_negotiation) = pending_splice.funding_negotiation.take() {
if let FundingNegotiation::ConstructingTransaction {
mut funding,
interactive_tx_constructor,
} = funding_negotiation
{
let signing_session = interactive_tx_constructor.into_signing_session();
let commitment_signed = chan.context.funding_tx_constructed(
pending_splice
.funding_negotiation
.take()
.and_then(|funding_negotiation| {
if let FundingNegotiation::ConstructingTransaction {
funding,
interactive_tx_constructor,
} = funding_negotiation
{
Some((funding, interactive_tx_constructor))
} else {
// Replace the taken state for later error handling
pending_splice.funding_negotiation = Some(funding_negotiation);
None
}
})
.ok_or_else(|| {
AbortReason::InternalError(
"Got a tx_complete message in an invalid state",
)
})
.and_then(|(mut funding, interactive_tx_constructor)| {
match chan.context.funding_tx_constructed(
&mut funding,
signing_session,
funding_outpoint,
true,
chan.holder_commitment_point.next_transaction_number(),
&&logger,
)?;

pending_splice.funding_negotiation =
Some(FundingNegotiation::AwaitingSignatures { funding });

return Ok(commitment_signed);
} else {
// Replace the taken state
pending_splice.funding_negotiation = Some(funding_negotiation);
}
}
) {
Ok(commitment_signed) => {
// Advance the state
pending_splice.funding_negotiation =
Some(FundingNegotiation::AwaitingSignatures { funding });
Ok((interactive_tx_constructor, commitment_signed))
},
Err(e) => {
// Restore the taken state for later error handling
pending_splice.funding_negotiation =
Some(FundingNegotiation::ConstructingTransaction {
funding,
interactive_tx_constructor,
});
Err(e)
},
}
})?
} else {
return Err(AbortReason::InternalError(
"Got a tx_complete message in an invalid state",
));
}

return Err(AbortReason::InternalError(
"Got a tx_complete message in an invalid state",
));
},
_ => {
debug_assert!(false);
return Err(AbortReason::InternalError(
"Got a tx_complete message in an invalid phase",
));
},
}
};

let signing_session = interactive_tx_constructor.into_signing_session();
self.context_mut().interactive_tx_signing_session = Some(signing_session);
Ok(commitment_signed)
}

pub fn force_shutdown(&mut self, closure_reason: ClosureReason) -> ShutdownResult {
Expand DownExpand Up@@ -6051,30 +6079,13 @@ where

#[rustfmt::skip]
fn funding_tx_constructed<L: Deref>(
&mut self, funding: &mut FundingScope, signing_session: InteractiveTxSigningSession,
is_splice: bool, holder_commitment_transaction_number: u64, logger: &L
&mut self, funding: &mut FundingScope, funding_outpoint: OutPoint, is_splice: bool,
holder_commitment_transaction_number: u64, logger: &L,
) -> Result<msgs::CommitmentSigned, AbortReason>
where
L::Target: Logger
{
let mut output_index = None;
let expected_spk = funding.get_funding_redeemscript().to_p2wsh();
for (idx, outp) in signing_session.unsigned_tx().tx().output.iter().enumerate() {
if outp.script_pubkey == expected_spk && outp.value.to_sat() == funding.get_value_satoshis() {
if output_index.is_some() {
return Err(AbortReason::DuplicateFundingOutput);
}
output_index = Some(idx as u16);
}
}
let outpoint = if let Some(output_index) = output_index {
OutPoint { txid: signing_session.unsigned_tx().compute_txid(), index: output_index }
} else {
return Err(AbortReason::MissingFundingOutput);
};
funding
.channel_transaction_parameters.funding_outpoint = Some(outpoint);
self.interactive_tx_signing_session = Some(signing_session);
funding.channel_transaction_parameters.funding_outpoint = Some(funding_outpoint);

if is_splice {
debug_assert_eq!(
Expand All@@ -6091,7 +6102,6 @@ where
Some(commitment_signed) => commitment_signed,
// TODO(splicing): Support async signing
None => {
funding.channel_transaction_parameters.funding_outpoint = None;
return Err(AbortReason::InternalError("Failed to compute commitment_signed signatures"));
},
};
Expand DownExpand Up@@ -6167,8 +6177,6 @@ where
SP::Target: SignerProvider,
L::Target: Logger,
{
debug_assert!(self.interactive_tx_signing_session.is_some());

let signatures = self.get_initial_counterparty_commitment_signatures(funding, logger);
if let Some((signature, htlc_signatures)) = signatures {
log_info!(
Expand DownExpand Up@@ -6508,9 +6516,9 @@ impl FundingNegotiationContext {
/// Prepare and start interactive transaction negotiation.
/// If error occurs, it is caused by our side, not the counterparty.
fn into_interactive_tx_constructor<SP: Deref, ES: Deref>(
self, context: &ChannelContext<SP>, funding: &FundingScope, signer_provider: &SP,
mut self, context: &ChannelContext<SP>, funding: &FundingScope, signer_provider: &SP,
entropy_source: &ES, holder_node_id: PublicKey,
) -> Result<InteractiveTxConstructor, AbortReason>
) -> Result<InteractiveTxConstructor, NegotiationError>
where
SP::Target: SignerProvider,
ES::Target: EntropySource,
Expand All@@ -6536,25 +6544,32 @@ impl FundingNegotiationContext {

// Optionally add change output
let change_value_opt = if self.our_funding_contribution > SignedAmount::ZERO {
calculate_change_output_value(
match calculate_change_output_value(
&self,
self.shared_funding_input.is_some(),
&shared_funding_output.script_pubkey,
context.holder_dust_limit_satoshis,
)?
) {
Ok(change_value_opt) => change_value_opt,
Err(reason) => {
return Err(self.into_negotiation_error(reason));
},
}
} else {
None
};

let mut funding_outputs = self.our_funding_outputs;

if let Some(change_value) = change_value_opt {
let change_script = if let Some(script) = self.change_script {
script
} else {
signer_provider
.get_destination_script(context.channel_keys_id)
.map_err(|_err| AbortReason::InternalError("Error getting change script"))?
match signer_provider.get_destination_script(context.channel_keys_id) {
Ok(script) => script,
Err(_) => {
let reason = AbortReason::InternalError("Error getting change script");
return Err(self.into_negotiation_error(reason));
},
}
};
let mut change_output =
TxOut { value: Amount::from_sat(change_value), script_pubkey: change_script };
Expand All@@ -6565,7 +6580,7 @@ impl FundingNegotiationContext {
// Check dust limit again
if change_value_decreased_with_fee > context.holder_dust_limit_satoshis {
change_output.value = Amount::from_sat(change_value_decreased_with_fee);
funding_outputs.push(change_output);
self.our_funding_outputs.push(change_output);
}
}

Expand All@@ -6583,10 +6598,19 @@ impl FundingNegotiationContext {
shared_funding_output,
funding.value_to_self_msat / 1000,
),
outputs_to_contribute: funding_outputs,
outputs_to_contribute: self.our_funding_outputs,
};
InteractiveTxConstructor::new(constructor_args)
}

fn into_negotiation_error(self, reason: AbortReason) -> NegotiationError {
let contributed_inputs =
self.our_funding_inputs.into_iter().map(|input| input.utxo.outpoint).collect();

let contributed_outputs = self.our_funding_outputs;

NegotiationError { reason, contributed_inputs, contributed_outputs }
}
}

// Holder designates channel data owned for the benefit of the user client.
Expand DownExpand Up@@ -13660,8 +13684,8 @@ where
outputs_to_contribute: funding_negotiation_context.our_funding_outputs.clone(),
}
).map_err(|err| {
let reason = ClosureReason::ProcessingError { err: err.to_string() };
ChannelError::Close((err.to_string(), reason))
let reason = ClosureReason::ProcessingError { err: err.reason.to_string() };
ChannelError::Close((err.reason.to_string(), reason))
})?);

let unfunded_context = UnfundedChannelContext {
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
Merged
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
178 changes: 101 additions & 77 deletions lightning/src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,7 +60,8 @@ use crate::ln::funding::{FundingTxInput, SpliceContribution};
use crate::ln::interactivetxs::{
calculate_change_output_value, get_output_weight, AbortReason, HandleTxCompleteValue,
InteractiveTxConstructor, InteractiveTxConstructorArgs, InteractiveTxMessageSend,
InteractiveTxSigningSession, SharedOwnedInput, SharedOwnedOutput, TX_COMMON_FIELDS_WEIGHT,
InteractiveTxSigningSession, NegotiationError, SharedOwnedInput, SharedOwnedOutput,
TX_COMMON_FIELDS_WEIGHT,
};
use crate::ln::msgs;
use crate::ln::msgs::{ClosingSigned, ClosingSignedFeeRange, DecodeError, OnionErrorPacket};
Expand DownExpand Up@@ -1794,20 +1795,22 @@ where

let (interactive_tx_msg_send, negotiation_complete) = match tx_complete_action {
HandleTxCompleteValue::SendTxMessage(interactive_tx_msg_send) => {
(Some(interactive_tx_msg_send), false)
(Some(interactive_tx_msg_send), None)
},
HandleTxCompleteValue::SendTxComplete(
HandleTxCompleteValue::NegotiationComplete(
interactive_tx_msg_send,
negotiation_complete,
) => (Some(interactive_tx_msg_send), negotiation_complete),
HandleTxCompleteValue::NegotiationComplete => (None, true),
funding_outpoint,
) => (interactive_tx_msg_send, Some(funding_outpoint)),
};
if !negotiation_complete {

let funding_outpoint = if let Some(funding_outpoint) = negotiation_complete {
funding_outpoint
} else {
return Ok((interactive_tx_msg_send, None));
}
};

let commitment_signed = self
.funding_tx_constructed(logger)
.funding_tx_constructed(funding_outpoint, logger)
.map_err(|abort_reason| self.fail_interactive_tx_negotiation(abort_reason, logger))?;
Ok((interactive_tx_msg_send, Some(commitment_signed)))
}
Expand DownExpand Up@@ -1890,13 +1893,13 @@ where
}

fn funding_tx_constructed<L: Deref>(
&mut self, logger: &L,
&mut self, funding_outpoint: OutPoint, logger: &L,
) -> Result<msgs::CommitmentSigned, AbortReason>
where
L::Target: Logger,
{
let logger = WithChannelContext::from(logger, self.context(), None);
match &mut self.phase {
let (interactive_tx_constructor, commitment_signed) = match &mut self.phase {
ChannelPhase::UnfundedV2(chan) => {
debug_assert_eq!(
chan.context.channel_state,
Expand All@@ -1906,60 +1909,85 @@ where
),
);

let signing_session = chan
let interactive_tx_constructor = chan
.interactive_tx_constructor
.take()
.expect("PendingV2Channel::interactive_tx_constructor should be set")
.into_signing_session();
.expect("PendingV2Channel::interactive_tx_constructor should be set");
let commitment_signed = chan.context.funding_tx_constructed(
&mut chan.funding,
signing_session,
funding_outpoint,
false,
chan.unfunded_context.transaction_number(),
&&logger,
)?;

return Ok(commitment_signed);
(interactive_tx_constructor, commitment_signed)
},
ChannelPhase::Funded(chan) => {
if let Some(pending_splice) = chan.pending_splice.as_mut() {
if let Some(funding_negotiation) = pending_splice.funding_negotiation.take() {
if let FundingNegotiation::ConstructingTransaction {
mut funding,
interactive_tx_constructor,
} = funding_negotiation
{
let signing_session = interactive_tx_constructor.into_signing_session();
let commitment_signed = chan.context.funding_tx_constructed(
pending_splice
.funding_negotiation
.take()
.and_then(|funding_negotiation| {
if let FundingNegotiation::ConstructingTransaction {
funding,
interactive_tx_constructor,
} = funding_negotiation
{
Some((funding, interactive_tx_constructor))
} else {
// Replace the taken state for later error handling
pending_splice.funding_negotiation = Some(funding_negotiation);
None
}
})
.ok_or_else(|| {
AbortReason::InternalError(
"Got a tx_complete message in an invalid state",
)
})
.and_then(|(mut funding, interactive_tx_constructor)| {
match chan.context.funding_tx_constructed(
&mut funding,
signing_session,
funding_outpoint,
true,
chan.holder_commitment_point.next_transaction_number(),
&&logger,
)?;

pending_splice.funding_negotiation =
Some(FundingNegotiation::AwaitingSignatures { funding });

return Ok(commitment_signed);
} else {
// Replace the taken state
pending_splice.funding_negotiation = Some(funding_negotiation);
}
}
) {
Ok(commitment_signed) => {
// Advance the state
pending_splice.funding_negotiation =
Some(FundingNegotiation::AwaitingSignatures { funding });
Ok((interactive_tx_constructor, commitment_signed))
},
Err(e) => {
// Restore the taken state for later error handling
pending_splice.funding_negotiation =
Some(FundingNegotiation::ConstructingTransaction {
funding,
interactive_tx_constructor,
});
Err(e)
},
}
})?
} else {
return Err(AbortReason::InternalError(
"Got a tx_complete message in an invalid state",
));
}

return Err(AbortReason::InternalError(
"Got a tx_complete message in an invalid state",
));
},
_ => {
debug_assert!(false);
return Err(AbortReason::InternalError(
"Got a tx_complete message in an invalid phase",
));
},
}
};

let signing_session = interactive_tx_constructor.into_signing_session();
self.context_mut().interactive_tx_signing_session = Some(signing_session);
Ok(commitment_signed)
}

pub fn force_shutdown(&mut self, closure_reason: ClosureReason) -> ShutdownResult {
Expand DownExpand Up@@ -6051,30 +6079,13 @@ where

#[rustfmt::skip]
fn funding_tx_constructed<L: Deref>(
&mut self, funding: &mut FundingScope, signing_session: InteractiveTxSigningSession,
is_splice: bool, holder_commitment_transaction_number: u64, logger: &L
&mut self, funding: &mut FundingScope, funding_outpoint: OutPoint, is_splice: bool,
holder_commitment_transaction_number: u64, logger: &L,
) -> Result<msgs::CommitmentSigned, AbortReason>
where
L::Target: Logger
{
let mut output_index = None;
let expected_spk = funding.get_funding_redeemscript().to_p2wsh();
for (idx, outp) in signing_session.unsigned_tx().tx().output.iter().enumerate() {
if outp.script_pubkey == expected_spk && outp.value.to_sat() == funding.get_value_satoshis() {
if output_index.is_some() {
return Err(AbortReason::DuplicateFundingOutput);
}
output_index = Some(idx as u16);
}
}
let outpoint = if let Some(output_index) = output_index {
OutPoint { txid: signing_session.unsigned_tx().compute_txid(), index: output_index }
} else {
return Err(AbortReason::MissingFundingOutput);
};
funding
.channel_transaction_parameters.funding_outpoint = Some(outpoint);
self.interactive_tx_signing_session = Some(signing_session);
funding.channel_transaction_parameters.funding_outpoint = Some(funding_outpoint);

if is_splice {
debug_assert_eq!(
Expand All@@ -6091,7 +6102,6 @@ where
Some(commitment_signed) => commitment_signed,
// TODO(splicing): Support async signing
None => {
funding.channel_transaction_parameters.funding_outpoint = None;
return Err(AbortReason::InternalError("Failed to compute commitment_signed signatures"));
},
};
Expand DownExpand Up@@ -6167,8 +6177,6 @@ where
SP::Target: SignerProvider,
L::Target: Logger,
{
debug_assert!(self.interactive_tx_signing_session.is_some());

let signatures = self.get_initial_counterparty_commitment_signatures(funding, logger);
if let Some((signature, htlc_signatures)) = signatures {
log_info!(
Expand DownExpand Up@@ -6508,9 +6516,9 @@ impl FundingNegotiationContext {
/// Prepare and start interactive transaction negotiation.
/// If error occurs, it is caused by our side, not the counterparty.
fn into_interactive_tx_constructor<SP: Deref, ES: Deref>(
self, context: &ChannelContext<SP>, funding: &FundingScope, signer_provider: &SP,
mut self, context: &ChannelContext<SP>, funding: &FundingScope, signer_provider: &SP,
entropy_source: &ES, holder_node_id: PublicKey,
) -> Result<InteractiveTxConstructor, AbortReason>
) -> Result<InteractiveTxConstructor, NegotiationError>
where
SP::Target: SignerProvider,
ES::Target: EntropySource,
Expand All@@ -6536,25 +6544,32 @@ impl FundingNegotiationContext {

// Optionally add change output
let change_value_opt = if self.our_funding_contribution > SignedAmount::ZERO {
calculate_change_output_value(
match calculate_change_output_value(
&self,
self.shared_funding_input.is_some(),
&shared_funding_output.script_pubkey,
context.holder_dust_limit_satoshis,
)?
) {
Ok(change_value_opt) => change_value_opt,
Err(reason) => {
return Err(self.into_negotiation_error(reason));
},
}
} else {
None
};

let mut funding_outputs = self.our_funding_outputs;

if let Some(change_value) = change_value_opt {
let change_script = if let Some(script) = self.change_script {
script
} else {
signer_provider
.get_destination_script(context.channel_keys_id)
.map_err(|_err| AbortReason::InternalError("Error getting change script"))?
match signer_provider.get_destination_script(context.channel_keys_id) {
Ok(script) => script,
Err(_) => {
let reason = AbortReason::InternalError("Error getting change script");
return Err(self.into_negotiation_error(reason));
},
}
};
let mut change_output =
TxOut { value: Amount::from_sat(change_value), script_pubkey: change_script };
Expand All@@ -6565,7 +6580,7 @@ impl FundingNegotiationContext {
// Check dust limit again
if change_value_decreased_with_fee > context.holder_dust_limit_satoshis {
change_output.value = Amount::from_sat(change_value_decreased_with_fee);
funding_outputs.push(change_output);
self.our_funding_outputs.push(change_output);
}
}

Expand All@@ -6583,10 +6598,19 @@ impl FundingNegotiationContext {
shared_funding_output,
funding.value_to_self_msat / 1000,
),
outputs_to_contribute: funding_outputs,
outputs_to_contribute: self.our_funding_outputs,
};
InteractiveTxConstructor::new(constructor_args)
}

fn into_negotiation_error(self, reason: AbortReason) -> NegotiationError {
let contributed_inputs =
self.our_funding_inputs.into_iter().map(|input| input.utxo.outpoint).collect();

let contributed_outputs = self.our_funding_outputs;

NegotiationError { reason, contributed_inputs, contributed_outputs }
}
}

// Holder designates channel data owned for the benefit of the user client.
Expand DownExpand Up@@ -13660,8 +13684,8 @@ where
outputs_to_contribute: funding_negotiation_context.our_funding_outputs.clone(),
}
).map_err(|err| {
let reason = ClosureReason::ProcessingError { err: err.to_string() };
ChannelError::Close((err.to_string(), reason))
let reason = ClosureReason::ProcessingError { err: err.reason.to_string() };
ChannelError::Close((err.reason.to_string(), reason))
})?);

let unfunded_context = UnfundedChannelContext {
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
Merged
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
178 changes: 101 additions & 77 deletions lightning/src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,7 +60,8 @@ use crate::ln::funding::{FundingTxInput, SpliceContribution};
use crate::ln::interactivetxs::{
calculate_change_output_value, get_output_weight, AbortReason, HandleTxCompleteValue,
InteractiveTxConstructor, InteractiveTxConstructorArgs, InteractiveTxMessageSend,
InteractiveTxSigningSession, SharedOwnedInput, SharedOwnedOutput, TX_COMMON_FIELDS_WEIGHT,
InteractiveTxSigningSession, NegotiationError, SharedOwnedInput, SharedOwnedOutput,
TX_COMMON_FIELDS_WEIGHT,
};
use crate::ln::msgs;
use crate::ln::msgs::{ClosingSigned, ClosingSignedFeeRange, DecodeError, OnionErrorPacket};
Expand DownExpand Up@@ -1794,20 +1795,22 @@ where

let (interactive_tx_msg_send, negotiation_complete) = match tx_complete_action {
HandleTxCompleteValue::SendTxMessage(interactive_tx_msg_send) => {
(Some(interactive_tx_msg_send), false)
(Some(interactive_tx_msg_send), None)
},
HandleTxCompleteValue::SendTxComplete(
HandleTxCompleteValue::NegotiationComplete(
interactive_tx_msg_send,
negotiation_complete,
) => (Some(interactive_tx_msg_send), negotiation_complete),
HandleTxCompleteValue::NegotiationComplete => (None, true),
funding_outpoint,
) => (interactive_tx_msg_send, Some(funding_outpoint)),
};
if !negotiation_complete {

let funding_outpoint = if let Some(funding_outpoint) = negotiation_complete {
funding_outpoint
} else {
return Ok((interactive_tx_msg_send, None));
}
};

let commitment_signed = self
.funding_tx_constructed(logger)
.funding_tx_constructed(funding_outpoint, logger)
.map_err(|abort_reason| self.fail_interactive_tx_negotiation(abort_reason, logger))?;
Ok((interactive_tx_msg_send, Some(commitment_signed)))
}
Expand DownExpand Up@@ -1890,13 +1893,13 @@ where
}

fn funding_tx_constructed<L: Deref>(
&mut self, logger: &L,
&mut self, funding_outpoint: OutPoint, logger: &L,
) -> Result<msgs::CommitmentSigned, AbortReason>
where
L::Target: Logger,
{
let logger = WithChannelContext::from(logger, self.context(), None);
match &mut self.phase {
let (interactive_tx_constructor, commitment_signed) = match &mut self.phase {
ChannelPhase::UnfundedV2(chan) => {
debug_assert_eq!(
chan.context.channel_state,
Expand All@@ -1906,60 +1909,85 @@ where
),
);

let signing_session = chan
let interactive_tx_constructor = chan
.interactive_tx_constructor
.take()
.expect("PendingV2Channel::interactive_tx_constructor should be set")
.into_signing_session();
.expect("PendingV2Channel::interactive_tx_constructor should be set");
let commitment_signed = chan.context.funding_tx_constructed(
&mut chan.funding,
signing_session,
funding_outpoint,
false,
chan.unfunded_context.transaction_number(),
&&logger,
)?;

return Ok(commitment_signed);
(interactive_tx_constructor, commitment_signed)
},
ChannelPhase::Funded(chan) => {
if let Some(pending_splice) = chan.pending_splice.as_mut() {
if let Some(funding_negotiation) = pending_splice.funding_negotiation.take() {
if let FundingNegotiation::ConstructingTransaction {
mut funding,
interactive_tx_constructor,
} = funding_negotiation
{
let signing_session = interactive_tx_constructor.into_signing_session();
let commitment_signed = chan.context.funding_tx_constructed(
pending_splice
.funding_negotiation
.take()
.and_then(|funding_negotiation| {
if let FundingNegotiation::ConstructingTransaction {
funding,
interactive_tx_constructor,
} = funding_negotiation
{
Some((funding, interactive_tx_constructor))
} else {
// Replace the taken state for later error handling
pending_splice.funding_negotiation = Some(funding_negotiation);
None
}
})
.ok_or_else(|| {
AbortReason::InternalError(
"Got a tx_complete message in an invalid state",
)
})
.and_then(|(mut funding, interactive_tx_constructor)| {
match chan.context.funding_tx_constructed(
&mut funding,
signing_session,
funding_outpoint,
true,
chan.holder_commitment_point.next_transaction_number(),
&&logger,
)?;

pending_splice.funding_negotiation =
Some(FundingNegotiation::AwaitingSignatures { funding });

return Ok(commitment_signed);
} else {
// Replace the taken state
pending_splice.funding_negotiation = Some(funding_negotiation);
}
}
) {
Ok(commitment_signed) => {
// Advance the state
pending_splice.funding_negotiation =
Some(FundingNegotiation::AwaitingSignatures { funding });
Ok((interactive_tx_constructor, commitment_signed))
},
Err(e) => {
// Restore the taken state for later error handling
pending_splice.funding_negotiation =
Some(FundingNegotiation::ConstructingTransaction {
funding,
interactive_tx_constructor,
});
Err(e)
},
}
})?
} else {
return Err(AbortReason::InternalError(
"Got a tx_complete message in an invalid state",
));
}

return Err(AbortReason::InternalError(
"Got a tx_complete message in an invalid state",
));
},
_ => {
debug_assert!(false);
return Err(AbortReason::InternalError(
"Got a tx_complete message in an invalid phase",
));
},
}
};

let signing_session = interactive_tx_constructor.into_signing_session();
self.context_mut().interactive_tx_signing_session = Some(signing_session);
Ok(commitment_signed)
}

pub fn force_shutdown(&mut self, closure_reason: ClosureReason) -> ShutdownResult {
Expand DownExpand Up@@ -6051,30 +6079,13 @@ where

#[rustfmt::skip]
fn funding_tx_constructed<L: Deref>(
&mut self, funding: &mut FundingScope, signing_session: InteractiveTxSigningSession,
is_splice: bool, holder_commitment_transaction_number: u64, logger: &L
&mut self, funding: &mut FundingScope, funding_outpoint: OutPoint, is_splice: bool,
holder_commitment_transaction_number: u64, logger: &L,
) -> Result<msgs::CommitmentSigned, AbortReason>
where
L::Target: Logger
{
let mut output_index = None;
let expected_spk = funding.get_funding_redeemscript().to_p2wsh();
for (idx, outp) in signing_session.unsigned_tx().tx().output.iter().enumerate() {
if outp.script_pubkey == expected_spk && outp.value.to_sat() == funding.get_value_satoshis() {
if output_index.is_some() {
return Err(AbortReason::DuplicateFundingOutput);
}
output_index = Some(idx as u16);
}
}
let outpoint = if let Some(output_index) = output_index {
OutPoint { txid: signing_session.unsigned_tx().compute_txid(), index: output_index }
} else {
return Err(AbortReason::MissingFundingOutput);
};
funding
.channel_transaction_parameters.funding_outpoint = Some(outpoint);
self.interactive_tx_signing_session = Some(signing_session);
funding.channel_transaction_parameters.funding_outpoint = Some(funding_outpoint);

if is_splice {
debug_assert_eq!(
Expand All@@ -6091,7 +6102,6 @@ where
Some(commitment_signed) => commitment_signed,
// TODO(splicing): Support async signing
None => {
funding.channel_transaction_parameters.funding_outpoint = None;
return Err(AbortReason::InternalError("Failed to compute commitment_signed signatures"));
},
};
Expand DownExpand Up@@ -6167,8 +6177,6 @@ where
SP::Target: SignerProvider,
L::Target: Logger,
{
debug_assert!(self.interactive_tx_signing_session.is_some());

let signatures = self.get_initial_counterparty_commitment_signatures(funding, logger);
if let Some((signature, htlc_signatures)) = signatures {
log_info!(
Expand DownExpand Up@@ -6508,9 +6516,9 @@ impl FundingNegotiationContext {
/// Prepare and start interactive transaction negotiation.
/// If error occurs, it is caused by our side, not the counterparty.
fn into_interactive_tx_constructor<SP: Deref, ES: Deref>(
self, context: &ChannelContext<SP>, funding: &FundingScope, signer_provider: &SP,
mut self, context: &ChannelContext<SP>, funding: &FundingScope, signer_provider: &SP,
entropy_source: &ES, holder_node_id: PublicKey,
) -> Result<InteractiveTxConstructor, AbortReason>
) -> Result<InteractiveTxConstructor, NegotiationError>
where
SP::Target: SignerProvider,
ES::Target: EntropySource,
Expand All@@ -6536,25 +6544,32 @@ impl FundingNegotiationContext {

// Optionally add change output
let change_value_opt = if self.our_funding_contribution > SignedAmount::ZERO {
calculate_change_output_value(
match calculate_change_output_value(
&self,
self.shared_funding_input.is_some(),
&shared_funding_output.script_pubkey,
context.holder_dust_limit_satoshis,
)?
) {
Ok(change_value_opt) => change_value_opt,
Err(reason) => {
return Err(self.into_negotiation_error(reason));
},
}
} else {
None
};

let mut funding_outputs = self.our_funding_outputs;

if let Some(change_value) = change_value_opt {
let change_script = if let Some(script) = self.change_script {
script
} else {
signer_provider
.get_destination_script(context.channel_keys_id)
.map_err(|_err| AbortReason::InternalError("Error getting change script"))?
match signer_provider.get_destination_script(context.channel_keys_id) {
Ok(script) => script,
Err(_) => {
let reason = AbortReason::InternalError("Error getting change script");
return Err(self.into_negotiation_error(reason));
},
}
};
let mut change_output =
TxOut { value: Amount::from_sat(change_value), script_pubkey: change_script };
Expand All@@ -6565,7 +6580,7 @@ impl FundingNegotiationContext {
// Check dust limit again
if change_value_decreased_with_fee > context.holder_dust_limit_satoshis {
change_output.value = Amount::from_sat(change_value_decreased_with_fee);
funding_outputs.push(change_output);
self.our_funding_outputs.push(change_output);
}
}

Expand All@@ -6583,10 +6598,19 @@ impl FundingNegotiationContext {
shared_funding_output,
funding.value_to_self_msat / 1000,
),
outputs_to_contribute: funding_outputs,
outputs_to_contribute: self.our_funding_outputs,
};
InteractiveTxConstructor::new(constructor_args)
}

fn into_negotiation_error(self, reason: AbortReason) -> NegotiationError {
let contributed_inputs =
self.our_funding_inputs.into_iter().map(|input| input.utxo.outpoint).collect();

let contributed_outputs = self.our_funding_outputs;

NegotiationError { reason, contributed_inputs, contributed_outputs }
}
}

// Holder designates channel data owned for the benefit of the user client.
Expand DownExpand Up@@ -13660,8 +13684,8 @@ where
outputs_to_contribute: funding_negotiation_context.our_funding_outputs.clone(),
}
).map_err(|err| {
let reason = ClosureReason::ProcessingError { err: err.to_string() };
ChannelError::Close((err.to_string(), reason))
let reason = ClosureReason::ProcessingError { err: err.reason.to_string() };
ChannelError::Close((err.reason.to_string(), reason))
})?);

let unfunded_context = UnfundedChannelContext {
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
Merged
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
178 changes: 101 additions & 77 deletions lightning/src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,7 +60,8 @@ use crate::ln::funding::{FundingTxInput, SpliceContribution};
use crate::ln::interactivetxs::{
calculate_change_output_value, get_output_weight, AbortReason, HandleTxCompleteValue,
InteractiveTxConstructor, InteractiveTxConstructorArgs, InteractiveTxMessageSend,
InteractiveTxSigningSession, SharedOwnedInput, SharedOwnedOutput, TX_COMMON_FIELDS_WEIGHT,
InteractiveTxSigningSession, NegotiationError, SharedOwnedInput, SharedOwnedOutput,
TX_COMMON_FIELDS_WEIGHT,
};
use crate::ln::msgs;
use crate::ln::msgs::{ClosingSigned, ClosingSignedFeeRange, DecodeError, OnionErrorPacket};
Expand DownExpand Up@@ -1794,20 +1795,22 @@ where

let (interactive_tx_msg_send, negotiation_complete) = match tx_complete_action {
HandleTxCompleteValue::SendTxMessage(interactive_tx_msg_send) => {
(Some(interactive_tx_msg_send), false)
(Some(interactive_tx_msg_send), None)
},
HandleTxCompleteValue::SendTxComplete(
HandleTxCompleteValue::NegotiationComplete(
interactive_tx_msg_send,
negotiation_complete,
) => (Some(interactive_tx_msg_send), negotiation_complete),
HandleTxCompleteValue::NegotiationComplete => (None, true),
funding_outpoint,
) => (interactive_tx_msg_send, Some(funding_outpoint)),
};
if !negotiation_complete {

let funding_outpoint = if let Some(funding_outpoint) = negotiation_complete {
funding_outpoint
} else {
return Ok((interactive_tx_msg_send, None));
}
};

let commitment_signed = self
.funding_tx_constructed(logger)
.funding_tx_constructed(funding_outpoint, logger)
.map_err(|abort_reason| self.fail_interactive_tx_negotiation(abort_reason, logger))?;
Ok((interactive_tx_msg_send, Some(commitment_signed)))
}
Expand DownExpand Up@@ -1890,13 +1893,13 @@ where
}

fn funding_tx_constructed<L: Deref>(
&mut self, logger: &L,
&mut self, funding_outpoint: OutPoint, logger: &L,
) -> Result<msgs::CommitmentSigned, AbortReason>
where
L::Target: Logger,
{
let logger = WithChannelContext::from(logger, self.context(), None);
match &mut self.phase {
let (interactive_tx_constructor, commitment_signed) = match &mut self.phase {
ChannelPhase::UnfundedV2(chan) => {
debug_assert_eq!(
chan.context.channel_state,
Expand All@@ -1906,60 +1909,85 @@ where
),
);

let signing_session = chan
let interactive_tx_constructor = chan
.interactive_tx_constructor
.take()
.expect("PendingV2Channel::interactive_tx_constructor should be set")
.into_signing_session();
.expect("PendingV2Channel::interactive_tx_constructor should be set");
let commitment_signed = chan.context.funding_tx_constructed(
&mut chan.funding,
signing_session,
funding_outpoint,
false,
chan.unfunded_context.transaction_number(),
&&logger,
)?;

return Ok(commitment_signed);
(interactive_tx_constructor, commitment_signed)
},
ChannelPhase::Funded(chan) => {
if let Some(pending_splice) = chan.pending_splice.as_mut() {
if let Some(funding_negotiation) = pending_splice.funding_negotiation.take() {
if let FundingNegotiation::ConstructingTransaction {
mut funding,
interactive_tx_constructor,
} = funding_negotiation
{
let signing_session = interactive_tx_constructor.into_signing_session();
let commitment_signed = chan.context.funding_tx_constructed(
pending_splice
.funding_negotiation
.take()
.and_then(|funding_negotiation| {
if let FundingNegotiation::ConstructingTransaction {
funding,
interactive_tx_constructor,
} = funding_negotiation
{
Some((funding, interactive_tx_constructor))
} else {
// Replace the taken state for later error handling
pending_splice.funding_negotiation = Some(funding_negotiation);
None
}
})
.ok_or_else(|| {
AbortReason::InternalError(
"Got a tx_complete message in an invalid state",
)
})
.and_then(|(mut funding, interactive_tx_constructor)| {
match chan.context.funding_tx_constructed(
&mut funding,
signing_session,
funding_outpoint,
true,
chan.holder_commitment_point.next_transaction_number(),
&&logger,
)?;

pending_splice.funding_negotiation =
Some(FundingNegotiation::AwaitingSignatures { funding });

return Ok(commitment_signed);
} else {
// Replace the taken state
pending_splice.funding_negotiation = Some(funding_negotiation);
}
}
) {
Ok(commitment_signed) => {
// Advance the state
pending_splice.funding_negotiation =
Some(FundingNegotiation::AwaitingSignatures { funding });
Ok((interactive_tx_constructor, commitment_signed))
},
Err(e) => {
// Restore the taken state for later error handling
pending_splice.funding_negotiation =
Some(FundingNegotiation::ConstructingTransaction {
funding,
interactive_tx_constructor,
});
Err(e)
},
}
})?
} else {
return Err(AbortReason::InternalError(
"Got a tx_complete message in an invalid state",
));
}

return Err(AbortReason::InternalError(
"Got a tx_complete message in an invalid state",
));
},
_ => {
debug_assert!(false);
return Err(AbortReason::InternalError(
"Got a tx_complete message in an invalid phase",
));
},
}
};

let signing_session = interactive_tx_constructor.into_signing_session();
self.context_mut().interactive_tx_signing_session = Some(signing_session);
Ok(commitment_signed)
}

pub fn force_shutdown(&mut self, closure_reason: ClosureReason) -> ShutdownResult {
Expand DownExpand Up@@ -6051,30 +6079,13 @@ where

#[rustfmt::skip]
fn funding_tx_constructed<L: Deref>(
&mut self, funding: &mut FundingScope, signing_session: InteractiveTxSigningSession,
is_splice: bool, holder_commitment_transaction_number: u64, logger: &L
&mut self, funding: &mut FundingScope, funding_outpoint: OutPoint, is_splice: bool,
holder_commitment_transaction_number: u64, logger: &L,
) -> Result<msgs::CommitmentSigned, AbortReason>
where
L::Target: Logger
{
let mut output_index = None;
let expected_spk = funding.get_funding_redeemscript().to_p2wsh();
for (idx, outp) in signing_session.unsigned_tx().tx().output.iter().enumerate() {
if outp.script_pubkey == expected_spk && outp.value.to_sat() == funding.get_value_satoshis() {
if output_index.is_some() {
return Err(AbortReason::DuplicateFundingOutput);
}
output_index = Some(idx as u16);
}
}
let outpoint = if let Some(output_index) = output_index {
OutPoint { txid: signing_session.unsigned_tx().compute_txid(), index: output_index }
} else {
return Err(AbortReason::MissingFundingOutput);
};
funding
.channel_transaction_parameters.funding_outpoint = Some(outpoint);
self.interactive_tx_signing_session = Some(signing_session);
funding.channel_transaction_parameters.funding_outpoint = Some(funding_outpoint);

if is_splice {
debug_assert_eq!(
Expand All@@ -6091,7 +6102,6 @@ where
Some(commitment_signed) => commitment_signed,
// TODO(splicing): Support async signing
None => {
funding.channel_transaction_parameters.funding_outpoint = None;
return Err(AbortReason::InternalError("Failed to compute commitment_signed signatures"));
},
};
Expand DownExpand Up@@ -6167,8 +6177,6 @@ where
SP::Target: SignerProvider,
L::Target: Logger,
{
debug_assert!(self.interactive_tx_signing_session.is_some());

let signatures = self.get_initial_counterparty_commitment_signatures(funding, logger);
if let Some((signature, htlc_signatures)) = signatures {
log_info!(
Expand DownExpand Up@@ -6508,9 +6516,9 @@ impl FundingNegotiationContext {
/// Prepare and start interactive transaction negotiation.
/// If error occurs, it is caused by our side, not the counterparty.
fn into_interactive_tx_constructor<SP: Deref, ES: Deref>(
self, context: &ChannelContext<SP>, funding: &FundingScope, signer_provider: &SP,
mut self, context: &ChannelContext<SP>, funding: &FundingScope, signer_provider: &SP,
entropy_source: &ES, holder_node_id: PublicKey,
) -> Result<InteractiveTxConstructor, AbortReason>
) -> Result<InteractiveTxConstructor, NegotiationError>
where
SP::Target: SignerProvider,
ES::Target: EntropySource,
Expand All@@ -6536,25 +6544,32 @@ impl FundingNegotiationContext {

// Optionally add change output
let change_value_opt = if self.our_funding_contribution > SignedAmount::ZERO {
calculate_change_output_value(
match calculate_change_output_value(
&self,
self.shared_funding_input.is_some(),
&shared_funding_output.script_pubkey,
context.holder_dust_limit_satoshis,
)?
) {
Ok(change_value_opt) => change_value_opt,
Err(reason) => {
return Err(self.into_negotiation_error(reason));
},
}
} else {
None
};

let mut funding_outputs = self.our_funding_outputs;

if let Some(change_value) = change_value_opt {
let change_script = if let Some(script) = self.change_script {
script
} else {
signer_provider
.get_destination_script(context.channel_keys_id)
.map_err(|_err| AbortReason::InternalError("Error getting change script"))?
match signer_provider.get_destination_script(context.channel_keys_id) {
Ok(script) => script,
Err(_) => {
let reason = AbortReason::InternalError("Error getting change script");
return Err(self.into_negotiation_error(reason));
},
}
};
let mut change_output =
TxOut { value: Amount::from_sat(change_value), script_pubkey: change_script };
Expand All@@ -6565,7 +6580,7 @@ impl FundingNegotiationContext {
// Check dust limit again
if change_value_decreased_with_fee > context.holder_dust_limit_satoshis {
change_output.value = Amount::from_sat(change_value_decreased_with_fee);
funding_outputs.push(change_output);
self.our_funding_outputs.push(change_output);
}
}

Expand All@@ -6583,10 +6598,19 @@ impl FundingNegotiationContext {
shared_funding_output,
funding.value_to_self_msat / 1000,
),
outputs_to_contribute: funding_outputs,
outputs_to_contribute: self.our_funding_outputs,
};
InteractiveTxConstructor::new(constructor_args)
}

fn into_negotiation_error(self, reason: AbortReason) -> NegotiationError {
let contributed_inputs =
self.our_funding_inputs.into_iter().map(|input| input.utxo.outpoint).collect();

let contributed_outputs = self.our_funding_outputs;

NegotiationError { reason, contributed_inputs, contributed_outputs }
}
}

// Holder designates channel data owned for the benefit of the user client.
Expand DownExpand Up@@ -13660,8 +13684,8 @@ where
outputs_to_contribute: funding_negotiation_context.our_funding_outputs.clone(),
}
).map_err(|err| {
let reason = ClosureReason::ProcessingError { err: err.to_string() };
ChannelError::Close((err.to_string(), reason))
let reason = ClosureReason::ProcessingError { err: err.reason.to_string() };
ChannelError::Close((err.reason.to_string(), reason))
})?);

let unfunded_context = UnfundedChannelContext {
Expand Down
Loading