Skip to content

Commit dbed102

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.
1 parent 42085b9 commit dbed102

File tree

4 files changed

+199
-35
lines changed

4 files changed

+199
-35
lines changed

lightning/src/events/mod.rs

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1654,6 +1654,48 @@ pub enum Event {
16541654
/// [`ChannelManager::send_static_invoice`]: crate::ln::channelmanager::ChannelManager::send_static_invoice
16551655
reply_path: Responder,
16561656
},
1657+
/// Indicates that a channel funding transaction constructed interactively is ready to be
1658+
/// signed. This event will only be triggered if at least one input was contributed.
1659+
///
1660+
/// The transaction contains all inputs provided by both parties along with the channel's funding
1661+
/// output and a change output if applicable.
1662+
///
1663+
/// No part of the transaction should be changed before signing as the content of the transaction
1664+
/// has already been negotiated with the counterparty.
1665+
///
1666+
/// Each signature MUST use the `SIGHASH_ALL` flag to avoid invalidation of the initial commitment and
1667+
/// hence possible loss of funds.
1668+
///
1669+
/// After signing, call [`ChannelManager::funding_transaction_signed`] with the (partially) signed
1670+
/// funding transaction.
1671+
///
1672+
/// Generated in [`ChannelManager`] message handling.
1673+
///
1674+
/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
1675+
/// [`ChannelManager::funding_transaction_signed`]: crate::ln::channelmanager::ChannelManager::funding_transaction_signed
1676+
FundingTransactionReadyForSigning {
1677+
/// The channel_id of the channel which you'll need to pass back into
1678+
/// [`ChannelManager::funding_transaction_signed`].
1679+
///
1680+
/// [`ChannelManager::funding_transaction_signed`]: crate::ln::channelmanager::ChannelManager::funding_transaction_signed
1681+
channel_id: ChannelId,
1682+
/// The counterparty's node_id, which you'll need to pass back into
1683+
/// [`ChannelManager::funding_transaction_signed`].
1684+
///
1685+
/// [`ChannelManager::funding_transaction_signed`]: crate::ln::channelmanager::ChannelManager::funding_transaction_signed
1686+
counterparty_node_id: PublicKey,
1687+
/// The `user_channel_id` value passed in for outbound channels, or for inbound channels if
1688+
/// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1689+
/// `user_channel_id` will be randomized for inbound channels.
1690+
///
1691+
/// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1692+
user_channel_id: u128,
1693+
/// The unsigned transaction to be signed and passed back to
1694+
/// [`ChannelManager::funding_transaction_signed`].
1695+
///
1696+
/// [`ChannelManager::funding_transaction_signed`]: crate::ln::channelmanager::ChannelManager::funding_transaction_signed
1697+
unsigned_transaction: Transaction,
1698+
},
16571699
}
16581700

16591701
impl Writeable for Event {
@@ -2095,6 +2137,13 @@ impl Writeable for Event {
20952137
47u8.write(writer)?;
20962138
// Never write StaticInvoiceRequested events as buffered onion messages aren't serialized.
20972139
},
2140+
&Event::FundingTransactionReadyForSigning { .. } => {
2141+
49u8.write(writer)?;
2142+
// We never write out FundingTransactionReadyForSigning events as, upon disconnection, peers
2143+
// drop any V2-established/spliced channels which have not yet exchanged the initial `commitment_signed`.
2144+
// We only exhange the initial `commitment_signed` after the client calls
2145+
// `ChannelManager::funding_transaction_signed` and ALWAYS before we send a `tx_signatures`
2146+
},
20982147
// Note that, going forward, all new events must only write data inside of
20992148
// `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
21002149
// data via `write_tlv_fields`.
@@ -2672,6 +2721,8 @@ impl MaybeReadable for Event {
26722721
// Note that we do not write a length-prefixed TLV for StaticInvoiceRequested events.
26732722
#[cfg(async_payments)]
26742723
47u8 => Ok(None),
2724+
// Note that we do not write a length-prefixed TLV for FundingTransactionReadyForSigning events.
2725+
49u8 => Ok(None),
26752726
// Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
26762727
// Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
26772728
// reads.

lightning/src/ln/channel.rs

Lines changed: 46 additions & 28 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;
@@ -1766,7 +1766,7 @@ where
17661766

17671767
pub fn funding_tx_constructed<L: Deref>(
17681768
&mut self, signing_session: InteractiveTxSigningSession, logger: &L,
1769-
) -> Result<(msgs::CommitmentSigned, Option<Event>), ChannelError>
1769+
) -> Result<(msgs::CommitmentSigned, Option<Transaction>), ChannelError>
17701770
where
17711771
L::Target: Logger,
17721772
{
@@ -2928,7 +2928,7 @@ where
29282928
#[rustfmt::skip]
29292929
pub fn funding_tx_constructed<L: Deref>(
29302930
&mut self, mut signing_session: InteractiveTxSigningSession, logger: &L
2931-
) -> Result<(msgs::CommitmentSigned, Option<Event>), ChannelError>
2931+
) -> Result<(msgs::CommitmentSigned, Option<Transaction>), ChannelError>
29322932
where
29332933
L::Target: Logger
29342934
{
@@ -2970,7 +2970,7 @@ where
29702970
},
29712971
};
29722972

2973-
let funding_ready_for_sig_event = if signing_session.local_inputs_count() == 0 {
2973+
let funding_tx_opt = if signing_session.local_inputs_count() == 0 {
29742974
debug_assert_eq!(our_funding_satoshis, 0);
29752975
if signing_session.provide_holder_witnesses(self.context.channel_id, Vec::new()).is_err() {
29762976
debug_assert!(
@@ -2984,28 +2984,7 @@ where
29842984
}
29852985
None
29862986
} else {
2987-
// TODO(dual_funding): Send event for signing if we've contributed funds.
2988-
// Inform the user that SIGHASH_ALL must be used for all signatures when contributing
2989-
// inputs/signatures.
2990-
// Also warn the user that we don't do anything to prevent the counterparty from
2991-
// providing non-standard witnesses which will prevent the funding transaction from
2992-
// confirming. This warning must appear in doc comments wherever the user is contributing
2993-
// funds, whether they are initiator or acceptor.
2994-
//
2995-
// The following warning can be used when the APIs allowing contributing inputs become available:
2996-
// <div class="warning">
2997-
// WARNING: LDK makes no attempt to prevent the counterparty from using non-standard inputs which
2998-
// will prevent the funding transaction from being relayed on the bitcoin network and hence being
2999-
// confirmed.
3000-
// </div>
3001-
debug_assert!(
3002-
false,
3003-
"We don't support users providing inputs but somehow we had more than zero inputs",
3004-
);
3005-
return Err(ChannelError::Close((
3006-
"V2 channel rejected due to sender error".into(),
3007-
ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(false) }
3008-
)));
2987+
Some(signing_session.unsigned_tx().build_unsigned_tx())
30092988
};
30102989

30112990
let mut channel_state = ChannelState::FundingNegotiated(FundingNegotiatedFlags::new());
@@ -3016,7 +2995,7 @@ where
30162995
self.interactive_tx_constructor.take();
30172996
self.interactive_tx_signing_session = Some(signing_session);
30182997

3019-
Ok((commitment_signed, funding_ready_for_sig_event))
2998+
Ok((commitment_signed, funding_tx_opt))
30202999
}
30213000
}
30223001

@@ -7612,6 +7591,45 @@ where
76127591
}
76137592
}
76147593

7594+
fn verify_interactive_tx_signatures(&mut self, _witnesses: &Vec<Witness>) {
7595+
if let Some(ref mut _signing_session) = self.interactive_tx_signing_session {
7596+
// Check that sighash_all was used:
7597+
// TODO(dual_funding): Check sig for sighash
7598+
}
7599+
}
7600+
7601+
pub fn funding_transaction_signed<L: Deref>(
7602+
&mut self, witnesses: Vec<Witness>, logger: &L,
7603+
) -> Result<Option<msgs::TxSignatures>, APIError>
7604+
where
7605+
L::Target: Logger,
7606+
{
7607+
self.verify_interactive_tx_signatures(&witnesses);
7608+
if let Some(ref mut signing_session) = self.interactive_tx_signing_session {
7609+
let logger = WithChannelContext::from(logger, &self.context, None);
7610+
if let Some(holder_tx_signatures) = signing_session
7611+
.provide_holder_witnesses(self.context.channel_id, witnesses)
7612+
.map_err(|err| APIError::APIMisuseError { err })?
7613+
{
7614+
if self.is_awaiting_initial_mon_persist() {
7615+
log_debug!(logger, "Not sending tx_signatures: a monitor update is in progress. Setting monitor_pending_tx_signatures.");
7616+
self.context.monitor_pending_tx_signatures = Some(holder_tx_signatures);
7617+
return Ok(None);
7618+
}
7619+
return Ok(Some(holder_tx_signatures));
7620+
} else {
7621+
return Ok(None);
7622+
}
7623+
} else {
7624+
return Err(APIError::APIMisuseError {
7625+
err: format!(
7626+
"Channel with id {} not expecting funding signatures",
7627+
self.context.channel_id
7628+
),
7629+
});
7630+
}
7631+
}
7632+
76157633
#[rustfmt::skip]
76167634
pub fn tx_signatures<L: Deref>(&mut self, msg: &msgs::TxSignatures, logger: &L) -> Result<(Option<Transaction>, Option<msgs::TxSignatures>), ChannelError>
76177635
where L::Target: Logger

lightning/src/ln/channelmanager.rs

Lines changed: 89 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5931,6 +5931,86 @@ where
59315931
result
59325932
}
59335933

5934+
/// Handles a signed funding transaction generated by interactive transaction construction and
5935+
/// provided by the client.
5936+
///
5937+
/// Do NOT broadcast the funding transaction yourself. When we have safely received our
5938+
/// counterparty's signature(s) the funding transaction will automatically be broadcast via the
5939+
/// [`BroadcasterInterface`] provided when this `ChannelManager` was constructed.
5940+
///
5941+
/// `SIGHASH_ALL` MUST be used for all signatures when providing signatures.
5942+
///
5943+
/// <div class="warning">
5944+
/// WARNING: LDK makes no attempt to prevent the counterparty from using non-standard inputs which
5945+
/// will prevent the funding transaction from being relayed on the bitcoin network and hence being
5946+
/// confirmed.
5947+
/// </div>
5948+
///
5949+
/// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
5950+
/// `counterparty_node_id` is provided.
5951+
///
5952+
/// Returns [`APIMisuseError`] when a channel is not in a state where it is expecting funding
5953+
/// signatures.
5954+
///
5955+
/// [`ChannelUnavailable`]: APIError::ChannelUnavailable
5956+
/// [`APIMisuseError`]: APIError::APIMisuseError
5957+
pub fn funding_transaction_signed(
5958+
&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, transaction: Transaction,
5959+
) -> Result<(), APIError> {
5960+
let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5961+
let witnesses: Vec<_> = transaction
5962+
.input
5963+
.into_iter()
5964+
.filter_map(|input| if input.witness.is_empty() { None } else { Some(input.witness) })
5965+
.collect();
5966+
5967+
let per_peer_state = self.per_peer_state.read().unwrap();
5968+
let peer_state_mutex = per_peer_state.get(counterparty_node_id).ok_or_else(|| {
5969+
APIError::ChannelUnavailable {
5970+
err: format!(
5971+
"Can't find a peer matching the passed counterparty node_id {}",
5972+
counterparty_node_id
5973+
),
5974+
}
5975+
})?;
5976+
5977+
let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5978+
let peer_state = &mut *peer_state_lock;
5979+
5980+
match peer_state.channel_by_id.get_mut(channel_id) {
5981+
Some(channel) => match channel.as_funded_mut() {
5982+
Some(chan) => {
5983+
if let Some(tx_signatures) =
5984+
chan.funding_transaction_signed(witnesses, &self.logger)?
5985+
{
5986+
peer_state.pending_msg_events.push(MessageSendEvent::SendTxSignatures {
5987+
node_id: *counterparty_node_id,
5988+
msg: tx_signatures,
5989+
});
5990+
}
5991+
},
5992+
None => {
5993+
return Err(APIError::APIMisuseError {
5994+
err: format!(
5995+
"Channel with id {} not expecting funding signatures",
5996+
channel_id
5997+
),
5998+
})
5999+
},
6000+
},
6001+
None => {
6002+
return Err(APIError::ChannelUnavailable {
6003+
err: format!(
6004+
"Channel with id {} not found for the passed counterparty node_id {}",
6005+
channel_id, counterparty_node_id
6006+
),
6007+
})
6008+
},
6009+
}
6010+
6011+
Ok(())
6012+
}
6013+
59346014
/// Atomically applies partial updates to the [`ChannelConfig`] of the given channels.
59356015
///
59366016
/// Once the updates are applied, each eligible channel (advertised with a known short channel
@@ -9057,13 +9137,19 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
90579137
peer_state.pending_msg_events.push(msg_send_event);
90589138
};
90599139
if let Some(signing_session) = signing_session_opt {
9060-
let (commitment_signed, funding_ready_for_sig_event_opt) = chan_entry
9140+
let (commitment_signed, funding_tx_opt) = chan_entry
90619141
.get_mut()
90629142
.funding_tx_constructed(signing_session, &self.logger)
90639143
.map_err(|err| MsgHandleErrInternal::send_err_msg_no_close(format!("{}", err), msg.channel_id))?;
9064-
if let Some(funding_ready_for_sig_event) = funding_ready_for_sig_event_opt {
9144+
if let Some(unsigned_transaction) = funding_tx_opt {
90659145
let mut pending_events = self.pending_events.lock().unwrap();
9066-
pending_events.push_back((funding_ready_for_sig_event, None));
9146+
pending_events.push_back((
9147+
Event::FundingTransactionReadyForSigning {
9148+
unsigned_transaction,
9149+
counterparty_node_id,
9150+
channel_id: msg.channel_id,
9151+
user_channel_id: chan_entry.get().context().get_user_id(),
9152+
}, None));
90679153
}
90689154
peer_state.pending_msg_events.push(MessageSendEvent::UpdateHTLCs {
90699155
node_id: counterparty_node_id,

lightning/src/ln/interactivetxs.rs

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -396,9 +396,14 @@ impl InteractiveTxSigningSession {
396396
/// unsigned transaction.
397397
pub fn provide_holder_witnesses(
398398
&mut self, channel_id: ChannelId, witnesses: Vec<Witness>,
399-
) -> Result<(), ()> {
400-
if self.local_inputs_count() != witnesses.len() {
401-
return Err(());
399+
) -> Result<Option<TxSignatures>, String> {
400+
let local_inputs_count = self.local_inputs_count();
401+
if local_inputs_count != witnesses.len() {
402+
return Err(format!(
403+
"Provided witness count of {} does not match required count for {} inputs",
404+
witnesses.len(),
405+
local_inputs_count
406+
));
402407
}
403408

404409
self.unsigned_tx.add_local_witnesses(witnesses.clone());
@@ -409,7 +414,11 @@ impl InteractiveTxSigningSession {
409414
shared_input_signature: None,
410415
});
411416

412-
Ok(())
417+
if self.holder_sends_tx_signatures_first && self.has_received_commitment_signed {
418+
Ok(self.holder_tx_signatures.clone())
419+
} else {
420+
Ok(None)
421+
}
413422
}
414423

415424
pub fn remote_inputs_count(&self) -> usize {

0 commit comments

Comments
 (0)