Skip to content

Commit 0a586e6

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 6771d84 commit 0a586e6

File tree

4 files changed

+201
-35
lines changed

4 files changed

+201
-35
lines changed

lightning/src/events/mod.rs

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1582,6 +1582,48 @@ pub enum Event {
15821582
/// onion messages.
15831583
peer_node_id: PublicKey,
15841584
},
1585+
/// Indicates that a channel funding transaction constructed interactively is ready to be
1586+
/// signed. This event will only be triggered if at least one input was contributed.
1587+
///
1588+
/// The transaction contains all inputs provided by both parties along with the channel's funding
1589+
/// output and a change output if applicable.
1590+
///
1591+
/// No part of the transaction should be changed before signing as the content of the transaction
1592+
/// has already been negotiated with the counterparty.
1593+
///
1594+
/// Each signature MUST use the `SIGHASH_ALL` flag to avoid invalidation of the initial commitment and
1595+
/// hence possible loss of funds.
1596+
///
1597+
/// After signing, call [`ChannelManager::funding_transaction_signed`] with the (partially) signed
1598+
/// funding transaction.
1599+
///
1600+
/// Generated in [`ChannelManager`] message handling.
1601+
///
1602+
/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
1603+
/// [`ChannelManager::funding_transaction_signed`]: crate::ln::channelmanager::ChannelManager::funding_transaction_signed
1604+
FundingTransactionReadyForSigning {
1605+
/// The channel_id of the channel which you'll need to pass back into
1606+
/// [`ChannelManager::funding_transaction_signed`].
1607+
///
1608+
/// [`ChannelManager::funding_transaction_signed`]: crate::ln::channelmanager::ChannelManager::funding_transaction_signed
1609+
channel_id: ChannelId,
1610+
/// The counterparty's node_id, which you'll need to pass back into
1611+
/// [`ChannelManager::funding_transaction_signed`].
1612+
///
1613+
/// [`ChannelManager::funding_transaction_signed`]: crate::ln::channelmanager::ChannelManager::funding_transaction_signed
1614+
counterparty_node_id: PublicKey,
1615+
/// The `user_channel_id` value passed in for outbound channels, or for inbound channels if
1616+
/// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1617+
/// `user_channel_id` will be randomized for inbound channels.
1618+
///
1619+
/// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1620+
user_channel_id: u128,
1621+
/// The unsigned transaction to be signed and passed back to
1622+
/// [`ChannelManager::funding_transaction_signed`].
1623+
///
1624+
/// [`ChannelManager::funding_transaction_signed`]: crate::ln::channelmanager::ChannelManager::funding_transaction_signed
1625+
unsigned_transaction: Transaction,
1626+
},
15851627
}
15861628

15871629
impl Writeable for Event {
@@ -2012,6 +2054,13 @@ impl Writeable for Event {
20122054
(8, former_temporary_channel_id, required),
20132055
});
20142056
},
2057+
&Event::FundingTransactionReadyForSigning { .. } => {
2058+
45u8.write(writer)?;
2059+
// We never write out FundingTransactionReadyForSigning events as, upon disconnection, peers
2060+
// drop any V2-established/spliced channels which have not yet exchanged the initial `commitment_signed`.
2061+
// We only exhange the initial `commitment_signed` after the client calls
2062+
// `ChannelManager::funding_transaction_signed` and ALWAYS before we send a `tx_signatures`
2063+
},
20152064
// Note that, going forward, all new events must only write data inside of
20162065
// `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
20172066
// data via `write_tlv_fields`.
@@ -2583,6 +2632,10 @@ impl MaybeReadable for Event {
25832632
former_temporary_channel_id: former_temporary_channel_id.0.unwrap(),
25842633
}))
25852634
},
2635+
45u8 => {
2636+
// Value 45 is used for `Event::FundingTransactionReadyForSigning`.
2637+
Ok(None)
2638+
},
25862639
// Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
25872640
// Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
25882641
// 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;
@@ -35,7 +35,7 @@ use crate::chain::channelmonitor::{
3535
use crate::chain::transaction::{OutPoint, TransactionData};
3636
use crate::chain::BestBlock;
3737
use crate::events::bump_transaction::BASE_INPUT_WEIGHT;
38-
use crate::events::{ClosureReason, Event};
38+
use crate::events::ClosureReason;
3939
use crate::ln::chan_utils;
4040
#[cfg(splicing)]
4141
use crate::ln::chan_utils::FUNDING_TRANSACTION_WITNESS_WEIGHT;
@@ -1763,7 +1763,7 @@ where
17631763

17641764
pub fn funding_tx_constructed<L: Deref>(
17651765
&mut self, signing_session: InteractiveTxSigningSession, logger: &L,
1766-
) -> Result<(msgs::CommitmentSigned, Option<Event>), ChannelError>
1766+
) -> Result<(msgs::CommitmentSigned, Option<Transaction>), ChannelError>
17671767
where
17681768
L::Target: Logger,
17691769
{
@@ -2925,7 +2925,7 @@ where
29252925
#[rustfmt::skip]
29262926
pub fn funding_tx_constructed<L: Deref>(
29272927
&mut self, mut signing_session: InteractiveTxSigningSession, logger: &L
2928-
) -> Result<(msgs::CommitmentSigned, Option<Event>), ChannelError>
2928+
) -> Result<(msgs::CommitmentSigned, Option<Transaction>), ChannelError>
29292929
where
29302930
L::Target: Logger
29312931
{
@@ -2967,7 +2967,7 @@ where
29672967
},
29682968
};
29692969

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

30082987
let mut channel_state = ChannelState::FundingNegotiated(FundingNegotiatedFlags::new());
@@ -3013,7 +2992,7 @@ where
30132992
self.interactive_tx_constructor.take();
30142993
self.interactive_tx_signing_session = Some(signing_session);
30152994

3016-
Ok((commitment_signed, funding_ready_for_sig_event))
2995+
Ok((commitment_signed, funding_tx_opt))
30172996
}
30182997
}
30192998

@@ -7640,6 +7619,45 @@ where
76407619
}
76417620
}
76427621

7622+
fn verify_interactive_tx_signatures(&mut self, _witnesses: &Vec<Witness>) {
7623+
if let Some(ref mut _signing_session) = self.interactive_tx_signing_session {
7624+
// Check that sighash_all was used:
7625+
// TODO(dual_funding): Check sig for sighash
7626+
}
7627+
}
7628+
7629+
pub fn funding_transaction_signed<L: Deref>(
7630+
&mut self, witnesses: Vec<Witness>, logger: &L,
7631+
) -> Result<Option<msgs::TxSignatures>, APIError>
7632+
where
7633+
L::Target: Logger,
7634+
{
7635+
self.verify_interactive_tx_signatures(&witnesses);
7636+
if let Some(ref mut signing_session) = self.interactive_tx_signing_session {
7637+
let logger = WithChannelContext::from(logger, &self.context, None);
7638+
if let Some(holder_tx_signatures) = signing_session
7639+
.provide_holder_witnesses(self.context.channel_id, witnesses)
7640+
.map_err(|err| APIError::APIMisuseError { err })?
7641+
{
7642+
if self.is_awaiting_initial_mon_persist() {
7643+
log_debug!(logger, "Not sending tx_signatures: a monitor update is in progress. Setting monitor_pending_tx_signatures.");
7644+
self.context.monitor_pending_tx_signatures = Some(holder_tx_signatures);
7645+
return Ok(None);
7646+
}
7647+
return Ok(Some(holder_tx_signatures));
7648+
} else {
7649+
return Ok(None);
7650+
}
7651+
} else {
7652+
return Err(APIError::APIMisuseError {
7653+
err: format!(
7654+
"Channel with id {} not expecting funding signatures",
7655+
self.context.channel_id
7656+
),
7657+
});
7658+
}
7659+
}
7660+
76437661
#[rustfmt::skip]
76447662
pub fn tx_signatures<L: Deref>(&mut self, msg: &msgs::TxSignatures, logger: &L) -> Result<(Option<Transaction>, Option<msgs::TxSignatures>), ChannelError>
76457663
where L::Target: Logger

lightning/src/ln/channelmanager.rs

Lines changed: 89 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5911,6 +5911,86 @@ where
59115911
result
59125912
}
59135913

5914+
/// Handles a signed funding transaction generated by interactive transaction construction and
5915+
/// provided by the client.
5916+
///
5917+
/// Do NOT broadcast the funding transaction yourself. When we have safely received our
5918+
/// counterparty's signature(s) the funding transaction will automatically be broadcast via the
5919+
/// [`BroadcasterInterface`] provided when this `ChannelManager` was constructed.
5920+
///
5921+
/// `SIGHASH_ALL` MUST be used for all signatures when providing signatures.
5922+
///
5923+
/// <div class="warning">
5924+
/// WARNING: LDK makes no attempt to prevent the counterparty from using non-standard inputs which
5925+
/// will prevent the funding transaction from being relayed on the bitcoin network and hence being
5926+
/// confirmed.
5927+
/// </div>
5928+
///
5929+
/// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
5930+
/// `counterparty_node_id` is provided.
5931+
///
5932+
/// Returns [`APIMisuseError`] when a channel is not in a state where it is expecting funding
5933+
/// signatures.
5934+
///
5935+
/// [`ChannelUnavailable`]: APIError::ChannelUnavailable
5936+
/// [`APIMisuseError`]: APIError::APIMisuseError
5937+
pub fn funding_transaction_signed(
5938+
&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, transaction: Transaction,
5939+
) -> Result<(), APIError> {
5940+
let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5941+
let witnesses: Vec<_> = transaction
5942+
.input
5943+
.into_iter()
5944+
.filter_map(|input| if input.witness.is_empty() { None } else { Some(input.witness) })
5945+
.collect();
5946+
5947+
let per_peer_state = self.per_peer_state.read().unwrap();
5948+
let peer_state_mutex = per_peer_state.get(counterparty_node_id).ok_or_else(|| {
5949+
APIError::ChannelUnavailable {
5950+
err: format!(
5951+
"Can't find a peer matching the passed counterparty node_id {}",
5952+
counterparty_node_id
5953+
),
5954+
}
5955+
})?;
5956+
5957+
let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5958+
let peer_state = &mut *peer_state_lock;
5959+
5960+
match peer_state.channel_by_id.get_mut(channel_id) {
5961+
Some(channel) => match channel.as_funded_mut() {
5962+
Some(chan) => {
5963+
if let Some(tx_signatures) =
5964+
chan.funding_transaction_signed(witnesses, &self.logger)?
5965+
{
5966+
peer_state.pending_msg_events.push(MessageSendEvent::SendTxSignatures {
5967+
node_id: *counterparty_node_id,
5968+
msg: tx_signatures,
5969+
});
5970+
}
5971+
},
5972+
None => {
5973+
return Err(APIError::APIMisuseError {
5974+
err: format!(
5975+
"Channel with id {} not expecting funding signatures",
5976+
channel_id
5977+
),
5978+
})
5979+
},
5980+
},
5981+
None => {
5982+
return Err(APIError::ChannelUnavailable {
5983+
err: format!(
5984+
"Channel with id {} not found for the passed counterparty node_id {}",
5985+
channel_id, counterparty_node_id
5986+
),
5987+
})
5988+
},
5989+
}
5990+
5991+
Ok(())
5992+
}
5993+
59145994
/// Atomically applies partial updates to the [`ChannelConfig`] of the given channels.
59155995
///
59165996
/// Once the updates are applied, each eligible channel (advertised with a known short channel
@@ -9037,13 +9117,19 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
90379117
peer_state.pending_msg_events.push(msg_send_event);
90389118
};
90399119
if let Some(signing_session) = signing_session_opt {
9040-
let (commitment_signed, funding_ready_for_sig_event_opt) = chan_entry
9120+
let (commitment_signed, funding_tx_opt) = chan_entry
90419121
.get_mut()
90429122
.funding_tx_constructed(signing_session, &self.logger)
90439123
.map_err(|err| MsgHandleErrInternal::send_err_msg_no_close(format!("{}", err), msg.channel_id))?;
9044-
if let Some(funding_ready_for_sig_event) = funding_ready_for_sig_event_opt {
9124+
if let Some(unsigned_transaction) = funding_tx_opt {
90459125
let mut pending_events = self.pending_events.lock().unwrap();
9046-
pending_events.push_back((funding_ready_for_sig_event, None));
9126+
pending_events.push_back((
9127+
Event::FundingTransactionReadyForSigning {
9128+
unsigned_transaction,
9129+
counterparty_node_id,
9130+
channel_id: msg.channel_id,
9131+
user_channel_id: chan_entry.get().context().get_user_id(),
9132+
}, None));
90479133
}
90489134
peer_state.pending_msg_events.push(MessageSendEvent::UpdateHTLCs {
90499135
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)