Skip to content

Commit 448b007

Browse files
committed
Introduce FundingTransactionReadyForSignatures event
The `FundingTransactionReadyForSignatures` event requests witnesses from the client for their contributed inputs to an interactively constructed transaction. The client calls `ChannelManager::funding_transaction_signed` to provide the witnesses to LDK. The `handle_channel_resumption` method handles resumption from both a channel re-establish and a monitor update. When the corresponding monitor update for the commitment_signed message completes, we will push the event here. We can thus only ever provide holder signatures after a monitor update has completed. We can also get rid of the reestablish code involved with `monitor_pending_tx_signatures` and remove that field too.
1 parent bb48bbc commit 448b007

File tree

4 files changed

+253
-125
lines changed

4 files changed

+253
-125
lines changed

lightning/src/events/mod.rs

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1692,6 +1692,52 @@ pub enum Event {
16921692
/// [`ChannelManager::send_static_invoice`]: crate::ln::channelmanager::ChannelManager::send_static_invoice
16931693
reply_path: Responder,
16941694
},
1695+
/// Indicates that a channel funding transaction constructed interactively is ready to be
1696+
/// signed. This event will only be triggered if at least one input was contributed.
1697+
///
1698+
/// The transaction contains all inputs provided by both parties along with the channel's funding
1699+
/// output and a change output if applicable.
1700+
///
1701+
/// No part of the transaction should be changed before signing as the content of the transaction
1702+
/// has already been negotiated with the counterparty.
1703+
///
1704+
/// Each signature MUST use the `SIGHASH_ALL` flag to avoid invalidation of the initial commitment and
1705+
/// hence possible loss of funds.
1706+
///
1707+
/// After signing, call [`ChannelManager::funding_transaction_signed`] with the (partially) signed
1708+
/// funding transaction.
1709+
///
1710+
/// Generated in [`ChannelManager`] message handling.
1711+
///
1712+
/// # Failure Behavior and Persistence
1713+
/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1714+
/// returning `Err(ReplayEvent ())`), but will only be regenerated as needed after restarts.
1715+
///
1716+
/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
1717+
/// [`ChannelManager::funding_transaction_signed`]: crate::ln::channelmanager::ChannelManager::funding_transaction_signed
1718+
FundingTransactionReadyForSigning {
1719+
/// The channel_id of the channel which you'll need to pass back into
1720+
/// [`ChannelManager::funding_transaction_signed`].
1721+
///
1722+
/// [`ChannelManager::funding_transaction_signed`]: crate::ln::channelmanager::ChannelManager::funding_transaction_signed
1723+
channel_id: ChannelId,
1724+
/// The counterparty's node_id, which you'll need to pass back into
1725+
/// [`ChannelManager::funding_transaction_signed`].
1726+
///
1727+
/// [`ChannelManager::funding_transaction_signed`]: crate::ln::channelmanager::ChannelManager::funding_transaction_signed
1728+
counterparty_node_id: PublicKey,
1729+
/// The `user_channel_id` value passed in for outbound channels, or for inbound channels if
1730+
/// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1731+
/// `user_channel_id` will be randomized for inbound channels.
1732+
///
1733+
/// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1734+
user_channel_id: u128,
1735+
/// The unsigned transaction to be signed and passed back to
1736+
/// [`ChannelManager::funding_transaction_signed`].
1737+
///
1738+
/// [`ChannelManager::funding_transaction_signed`]: crate::ln::channelmanager::ChannelManager::funding_transaction_signed
1739+
unsigned_transaction: Transaction,
1740+
},
16951741
}
16961742

16971743
impl Writeable for Event {
@@ -2133,6 +2179,11 @@ impl Writeable for Event {
21332179
47u8.write(writer)?;
21342180
// Never write StaticInvoiceRequested events as buffered onion messages aren't serialized.
21352181
},
2182+
&Event::FundingTransactionReadyForSigning { .. } => {
2183+
49u8.write(writer)?;
2184+
// We never write out FundingTransactionReadyForSigning events as they will be regenerated when
2185+
// necessary.
2186+
},
21362187
// Note that, going forward, all new events must only write data inside of
21372188
// `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
21382189
// data via `write_tlv_fields`.
@@ -2715,6 +2766,8 @@ impl MaybeReadable for Event {
27152766
// Note that we do not write a length-prefixed TLV for StaticInvoiceRequested events.
27162767
#[cfg(async_payments)]
27172768
47u8 => Ok(None),
2769+
// Note that we do not write a length-prefixed TLV for FundingTransactionReadyForSigning events.
2770+
49u8 => Ok(None),
27182771
// Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
27192772
// Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
27202773
// reads.

lightning/src/ln/channel.rs

Lines changed: 53 additions & 107 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use bitcoin::constants::ChainHash;
1414
use bitcoin::script::{Builder, Script, ScriptBuf, WScriptHash};
1515
use bitcoin::sighash::EcdsaSighashType;
1616
use bitcoin::transaction::{Transaction, TxIn, TxOut};
17-
use bitcoin::Weight;
17+
use bitcoin::{Weight, Witness};
1818

1919
use bitcoin::hash_types::{BlockHash, Txid};
2020
use bitcoin::hashes::sha256::Hash as Sha256;
@@ -36,7 +36,7 @@ use crate::chain::channelmonitor::{
3636
use crate::chain::transaction::{OutPoint, TransactionData};
3737
use crate::chain::BestBlock;
3838
use crate::events::bump_transaction::BASE_INPUT_WEIGHT;
39-
use crate::events::{ClosureReason, Event};
39+
use crate::events::ClosureReason;
4040
use crate::ln::chan_utils;
4141
#[cfg(splicing)]
4242
use crate::ln::chan_utils::FUNDING_TRANSACTION_WITNESS_WEIGHT;
@@ -1761,7 +1761,7 @@ where
17611761

17621762
pub fn funding_tx_constructed<L: Deref>(
17631763
&mut self, signing_session: InteractiveTxSigningSession, logger: &L,
1764-
) -> Result<(msgs::CommitmentSigned, Option<Event>), ChannelError>
1764+
) -> Result<msgs::CommitmentSigned, ChannelError>
17651765
where
17661766
L::Target: Logger,
17671767
{
@@ -2310,7 +2310,6 @@ where
23102310
monitor_pending_failures: Vec<(HTLCSource, PaymentHash, HTLCFailReason)>,
23112311
monitor_pending_finalized_fulfills: Vec<(HTLCSource, Option<AttributionData>)>,
23122312
monitor_pending_update_adds: Vec<msgs::UpdateAddHTLC>,
2313-
monitor_pending_tx_signatures: Option<msgs::TxSignatures>,
23142313

23152314
/// If we went to send a revoke_and_ack but our signer was unable to give us a signature,
23162315
/// we should retry at some point in the future when the signer indicates it may have a
@@ -2910,12 +2909,11 @@ where
29102909

29112910
#[rustfmt::skip]
29122911
pub fn funding_tx_constructed<L: Deref>(
2913-
&mut self, mut signing_session: InteractiveTxSigningSession, logger: &L
2914-
) -> Result<(msgs::CommitmentSigned, Option<Event>), ChannelError>
2912+
&mut self, signing_session: InteractiveTxSigningSession, logger: &L
2913+
) -> Result<msgs::CommitmentSigned, ChannelError>
29152914
where
29162915
L::Target: Logger
29172916
{
2918-
let our_funding_satoshis = self.dual_funding_context.our_funding_satoshis;
29192917
let transaction_number = self.unfunded_context.transaction_number();
29202918

29212919
let mut output_index = None;
@@ -2949,42 +2947,6 @@ where
29492947
},
29502948
};
29512949

2952-
let funding_ready_for_sig_event = if signing_session.local_inputs_count() == 0 {
2953-
debug_assert_eq!(our_funding_satoshis, 0);
2954-
if signing_session.provide_holder_witnesses(self.context.channel_id, Vec::new()).is_err() {
2955-
debug_assert!(
2956-
false,
2957-
"Zero inputs were provided & zero witnesses were provided, but a count mismatch was somehow found",
2958-
);
2959-
let msg = "V2 channel rejected due to sender error";
2960-
let reason = ClosureReason::ProcessingError { err: msg.to_owned() };
2961-
return Err(ChannelError::Close((msg.to_owned(), reason)));
2962-
}
2963-
None
2964-
} else {
2965-
// TODO(dual_funding): Send event for signing if we've contributed funds.
2966-
// Inform the user that SIGHASH_ALL must be used for all signatures when contributing
2967-
// inputs/signatures.
2968-
// Also warn the user that we don't do anything to prevent the counterparty from
2969-
// providing non-standard witnesses which will prevent the funding transaction from
2970-
// confirming. This warning must appear in doc comments wherever the user is contributing
2971-
// funds, whether they are initiator or acceptor.
2972-
//
2973-
// The following warning can be used when the APIs allowing contributing inputs become available:
2974-
// <div class="warning">
2975-
// WARNING: LDK makes no attempt to prevent the counterparty from using non-standard inputs which
2976-
// will prevent the funding transaction from being relayed on the bitcoin network and hence being
2977-
// confirmed.
2978-
// </div>
2979-
debug_assert!(
2980-
false,
2981-
"We don't support users providing inputs but somehow we had more than zero inputs",
2982-
);
2983-
let msg = "V2 channel rejected due to sender error";
2984-
let reason = ClosureReason::ProcessingError { err: msg.to_owned() };
2985-
return Err(ChannelError::Close((msg.to_owned(), reason)));
2986-
};
2987-
29882950
let mut channel_state = ChannelState::FundingNegotiated(FundingNegotiatedFlags::new());
29892951
channel_state.set_interactive_signing();
29902952
self.context.channel_state = channel_state;
@@ -2993,7 +2955,7 @@ where
29932955
self.interactive_tx_constructor.take();
29942956
self.interactive_tx_signing_session = Some(signing_session);
29952957

2996-
Ok((commitment_signed, funding_ready_for_sig_event))
2958+
Ok(commitment_signed)
29972959
}
29982960
}
29992961

@@ -3275,7 +3237,6 @@ where
32753237
monitor_pending_failures: Vec::new(),
32763238
monitor_pending_finalized_fulfills: Vec::new(),
32773239
monitor_pending_update_adds: Vec::new(),
3278-
monitor_pending_tx_signatures: None,
32793240

32803241
signer_pending_revoke_and_ack: false,
32813242
signer_pending_commitment_update: false,
@@ -3514,7 +3475,6 @@ where
35143475
monitor_pending_failures: Vec::new(),
35153476
monitor_pending_finalized_fulfills: Vec::new(),
35163477
monitor_pending_update_adds: Vec::new(),
3517-
monitor_pending_tx_signatures: None,
35183478

35193479
signer_pending_revoke_and_ack: false,
35203480
signer_pending_commitment_update: false,
@@ -6767,13 +6727,7 @@ where
67676727

67686728
self.monitor_updating_paused(false, false, false, Vec::new(), Vec::new(), Vec::new());
67696729

6770-
if let Some(tx_signatures) = self.interactive_tx_signing_session.as_mut().and_then(
6771-
|session| session.received_commitment_signed()
6772-
) {
6773-
// We're up first for submitting our tx_signatures, but our monitor has not persisted yet
6774-
// so they'll be sent as soon as that's done.
6775-
self.context.monitor_pending_tx_signatures = Some(tx_signatures);
6776-
}
6730+
self.interactive_tx_signing_session.as_mut().map(|session| session.received_commitment_signed());
67776731

67786732
Ok(channel_monitor)
67796733
}
@@ -6856,13 +6810,12 @@ where
68566810
channel_id: Some(self.context.channel_id()),
68576811
};
68586812

6859-
let tx_signatures = self
6813+
let _ = self
68606814
.interactive_tx_signing_session
68616815
.as_mut()
68626816
.expect("Signing session must exist for negotiated pending splice")
68636817
.received_commitment_signed();
68646818
self.monitor_updating_paused(false, false, false, Vec::new(), Vec::new(), Vec::new());
6865-
self.context.monitor_pending_tx_signatures = tx_signatures;
68666819

68676820
Ok(self.push_ret_blockable_mon_update(monitor_update))
68686821
}
@@ -7772,10 +7725,26 @@ where
77727725
}
77737726
}
77747727

7728+
pub fn funding_transaction_signed(
7729+
&mut self, witnesses: Vec<Witness>,
7730+
) -> Result<Option<msgs::TxSignatures>, APIError> {
7731+
self.interactive_tx_signing_session
7732+
.as_mut()
7733+
.ok_or_else(|| APIError::APIMisuseError {
7734+
err: format!(
7735+
"Channel with id {} not expecting funding signatures",
7736+
self.context.channel_id
7737+
),
7738+
})
7739+
.and_then(|signing_session| {
7740+
signing_session
7741+
.provide_holder_witnesses(self.context.channel_id, witnesses)
7742+
.map_err(|err| APIError::APIMisuseError { err })
7743+
})
7744+
}
7745+
77757746
#[rustfmt::skip]
7776-
pub fn tx_signatures<L: Deref>(&mut self, msg: &msgs::TxSignatures, logger: &L) -> Result<(Option<Transaction>, Option<msgs::TxSignatures>), ChannelError>
7777-
where L::Target: Logger
7778-
{
7747+
pub fn tx_signatures(&mut self, msg: &msgs::TxSignatures) -> Result<(Option<Transaction>, Option<msgs::TxSignatures>), ChannelError> {
77797748
if !self.context.channel_state.is_interactive_signing()
77807749
|| self.context.channel_state.is_their_tx_signatures_sent()
77817750
{
@@ -7828,15 +7797,8 @@ where
78287797
self.funding.funding_transaction = funding_tx_opt.clone();
78297798
}
78307799

7831-
// Note that `holder_tx_signatures_opt` will be `None` if we sent `tx_signatures` first, so this
7832-
// case checks if there is a monitor persist in progress when we need to respond with our `tx_signatures`
7833-
// and sets it as pending.
7834-
if holder_tx_signatures_opt.is_some() && self.is_awaiting_initial_mon_persist() {
7835-
log_debug!(logger, "Not sending tx_signatures: a monitor update is in progress. Setting monitor_pending_tx_signatures.");
7836-
self.context.monitor_pending_tx_signatures = holder_tx_signatures_opt;
7837-
return Ok((None, None));
7838-
}
7839-
7800+
// Note that `holder_tx_signatures_opt` will be `None` if we sent `tx_signatures` first or if the
7801+
// user still needs to provide tx_signatures and we are sending second.
78407802
if holder_tx_signatures_opt.is_some() {
78417803
self.context.channel_state.set_our_tx_signatures_ready();
78427804
}
@@ -8093,25 +8055,14 @@ where
80938055
mem::swap(&mut finalized_claimed_htlcs, &mut self.context.monitor_pending_finalized_fulfills);
80948056
let mut pending_update_adds = Vec::new();
80958057
mem::swap(&mut pending_update_adds, &mut self.context.monitor_pending_update_adds);
8096-
// For channels established with V2 establishment we won't send a `tx_signatures` when we're in
8097-
// MonitorUpdateInProgress (and we assume the user will never directly broadcast the funding
8098-
// transaction and waits for us to do it).
8099-
let tx_signatures = self.context.monitor_pending_tx_signatures.take();
8100-
if tx_signatures.is_some() {
8101-
if self.context.channel_state.is_their_tx_signatures_sent() {
8102-
self.context.channel_state = ChannelState::AwaitingChannelReady(AwaitingChannelReadyFlags::new());
8103-
} else {
8104-
self.context.channel_state.set_our_tx_signatures_ready();
8105-
}
8106-
}
81078058

81088059
if self.context.channel_state.is_peer_disconnected() {
81098060
self.context.monitor_pending_revoke_and_ack = false;
81108061
self.context.monitor_pending_commitment_signed = false;
81118062
return MonitorRestoreUpdates {
81128063
raa: None, commitment_update: None, order: RAACommitmentOrder::RevokeAndACKFirst,
81138064
accepted_htlcs, failed_htlcs, finalized_claimed_htlcs, pending_update_adds,
8114-
funding_broadcastable, channel_ready, announcement_sigs, tx_signatures
8065+
funding_broadcastable, channel_ready, announcement_sigs, tx_signatures: None
81158066
};
81168067
}
81178068

@@ -8141,7 +8092,7 @@ where
81418092
match order { RAACommitmentOrder::CommitmentFirst => "commitment", RAACommitmentOrder::RevokeAndACKFirst => "RAA"});
81428093
MonitorRestoreUpdates {
81438094
raa, commitment_update, order, accepted_htlcs, failed_htlcs, finalized_claimed_htlcs,
8144-
pending_update_adds, funding_broadcastable, channel_ready, announcement_sigs, tx_signatures
8095+
pending_update_adds, funding_broadcastable, channel_ready, announcement_sigs, tx_signatures: None
81458096
}
81468097
}
81478098

@@ -8416,23 +8367,25 @@ where
84168367
log_trace!(logger, "Regenerating latest commitment update in channel {} with{} {} update_adds, {} update_fulfills, {} update_fails, and {} update_fail_malformeds",
84178368
&self.context.channel_id(), if update_fee.is_some() { " update_fee," } else { "" },
84188369
update_add_htlcs.len(), update_fulfill_htlcs.len(), update_fail_htlcs.len(), update_fail_malformed_htlcs.len());
8419-
let commitment_signed =
8420-
if let Ok(update) = self.send_commitment_no_state_update(logger) {
8421-
if self.context.signer_pending_commitment_update {
8422-
log_trace!(
8423-
logger,
8424-
"Commitment update generated: clearing signer_pending_commitment_update"
8425-
);
8426-
self.context.signer_pending_commitment_update = false;
8427-
}
8428-
update
8429-
} else {
8430-
if !self.context.signer_pending_commitment_update {
8431-
log_trace!(logger, "Commitment update awaiting signer: setting signer_pending_commitment_update");
8432-
self.context.signer_pending_commitment_update = true;
8433-
}
8434-
return Err(());
8435-
};
8370+
let commitment_signed = if let Ok(update) = self.send_commitment_no_state_update(logger) {
8371+
if self.context.signer_pending_commitment_update {
8372+
log_trace!(
8373+
logger,
8374+
"Commitment update generated: clearing signer_pending_commitment_update"
8375+
);
8376+
self.context.signer_pending_commitment_update = false;
8377+
}
8378+
update
8379+
} else {
8380+
if !self.context.signer_pending_commitment_update {
8381+
log_trace!(
8382+
logger,
8383+
"Commitment update awaiting signer: setting signer_pending_commitment_update"
8384+
);
8385+
self.context.signer_pending_commitment_update = true;
8386+
}
8387+
return Err(());
8388+
};
84368389
Ok(msgs::CommitmentUpdate {
84378390
update_add_htlcs,
84388391
update_fulfill_htlcs,
@@ -8618,7 +8571,6 @@ where
86188571
update_fee: None,
86198572
})
86208573
} else { None };
8621-
// TODO(dual_funding): For async signing support we need to hold back `tx_signatures` until the `commitment_signed` is ready.
86228574
let tx_signatures = if (
86238575
// if it has not received tx_signatures for that funding transaction AND
86248576
// if it has already received commitment_signed AND it should sign first, as specified in the tx_signatures requirements:
@@ -8627,14 +8579,9 @@ where
86278579
// else if it has already received tx_signatures for that funding transaction:
86288580
// MUST send its tx_signatures for that funding transaction.
86298581
) || self.context.channel_state.is_their_tx_signatures_sent() {
8630-
if self.context.channel_state.is_monitor_update_in_progress() {
8631-
// The `monitor_pending_tx_signatures` field should have already been set in `commitment_signed_initial_v2`
8632-
// if we were up first for signing and had a monitor update in progress, but check again just in case.
8633-
debug_assert!(self.context.monitor_pending_tx_signatures.is_some(), "monitor_pending_tx_signatures should already be set");
8634-
log_debug!(logger, "Not sending tx_signatures: a monitor update is in progress. Setting monitor_pending_tx_signatures.");
8635-
if self.context.monitor_pending_tx_signatures.is_none() {
8636-
self.context.monitor_pending_tx_signatures = session.holder_tx_signatures().clone();
8637-
}
8582+
if session.holder_tx_signatures().is_none() {
8583+
debug_assert!(self.context.channel_state.is_monitor_update_in_progress());
8584+
log_debug!(logger, "Not sending tx_signatures: a monitor update is in progress.");
86388585
None
86398586
} else {
86408587
// If `holder_tx_signatures` is `None` here, the `tx_signatures` message will be sent
@@ -13559,7 +13506,6 @@ where
1355913506
monitor_pending_failures,
1356013507
monitor_pending_finalized_fulfills: monitor_pending_finalized_fulfills.unwrap(),
1356113508
monitor_pending_update_adds: monitor_pending_update_adds.unwrap_or_default(),
13562-
monitor_pending_tx_signatures: None,
1356313509

1356413510
signer_pending_revoke_and_ack: false,
1356513511
signer_pending_commitment_update: false,

0 commit comments

Comments
 (0)