Skip to content

Commit d6bd9fe

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 21d3c78 commit d6bd9fe

File tree

4 files changed

+161
-30
lines changed

4 files changed

+161
-30
lines changed

lightning/src/events/mod.rs

+57-1
Original file line numberDiff line numberDiff line change
@@ -1507,7 +1507,56 @@ pub enum Event {
15071507
/// The node id of the peer we just connected to, who advertises support for
15081508
/// onion messages.
15091509
peer_node_id: PublicKey,
1510-
}
1510+
},
1511+
/// Indicates that a funding transaction constructed via interactive transaction construction for a
1512+
/// channel is ready to be signed by the client. This event will only be triggered
1513+
/// if at least one input was contributed by the holder and needs to be signed.
1514+
///
1515+
/// The transaction contains all inputs provided by both parties along with the channel's funding
1516+
/// output and a change output if applicable.
1517+
///
1518+
/// No part of the transaction should be changed before signing as the content of the transaction
1519+
/// has already been negotiated with the counterparty.
1520+
///
1521+
/// Each signature MUST use the SIGHASH_ALL flag to avoid invalidation of the initial commitment and
1522+
/// hence possible loss of funds.
1523+
///
1524+
/// After signing, call [`ChannelManager::funding_transaction_signed`] with the (partially) signed
1525+
/// funding transaction.
1526+
///
1527+
/// Generated in [`ChannelManager`] message handling.
1528+
///
1529+
/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
1530+
/// [`ChannelManager::funding_transaction_signed`]: crate::ln::channelmanager::ChannelManager::funding_transaction_signed
1531+
FundingTransactionReadyForSigning {
1532+
/// The channel_id of the channel which you'll need to pass back into
1533+
/// [`ChannelManager::funding_transaction_signed`].
1534+
///
1535+
/// [`ChannelManager::funding_transaction_signed`]: crate::ln::channelmanager::ChannelManager::funding_transaction_signed
1536+
channel_id: ChannelId,
1537+
/// The counterparty's node_id, which you'll need to pass back into
1538+
/// [`ChannelManager::funding_transaction_signed`].
1539+
///
1540+
/// [`ChannelManager::funding_transaction_signed`]: crate::ln::channelmanager::ChannelManager::funding_transaction_signed
1541+
counterparty_node_id: PublicKey,
1542+
// TODO(dual_funding): Enable links when methods are implemented
1543+
/// The `user_channel_id` value passed in to `ChannelManager::create_dual_funded_channel` for outbound
1544+
/// channels, or to [`ChannelManager::accept_inbound_channel`] or `ChannelManager::accept_inbound_channel_with_contribution`
1545+
/// for inbound channels if [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
1546+
/// Otherwise `user_channel_id` will be randomized for an inbound channel.
1547+
/// This may be zero for objects serialized with LDK versions prior to 0.0.113.
1548+
///
1549+
/// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1550+
/// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1551+
// [`ChannelManager::create_dual_funded_channel`]: crate::ln::channelmanager::ChannelManager::create_dual_funded_channel
1552+
// [`ChannelManager::accept_inbound_channel_with_contribution`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel_with_contribution
1553+
user_channel_id: u128,
1554+
/// The unsigned transaction to be signed and passed back to
1555+
/// [`ChannelManager::funding_transaction_signed`].
1556+
///
1557+
/// [`ChannelManager::funding_transaction_signed`]: crate::ln::channelmanager::ChannelManager::funding_transaction_signed
1558+
unsigned_transaction: Transaction,
1559+
},
15111560
}
15121561

15131562
impl Writeable for Event {
@@ -1842,6 +1891,13 @@ impl Writeable for Event {
18421891
(8, former_temporary_channel_id, required),
18431892
});
18441893
},
1894+
&Event::FundingTransactionReadyForSigning { .. } => {
1895+
45u8.write(writer)?;
1896+
// We never write out FundingTransactionReadyForSigning events as, upon disconnection, peers
1897+
// drop any V2-established/spliced channels which have not yet exchanged the initial `commitment_signed`.
1898+
// We only exhange the initial `commitment_signed` after the client calls
1899+
// `ChannelManager::funding_transaction_signed` and ALWAYS before we send a `tx_signatures`
1900+
},
18451901
// Note that, going forward, all new events must only write data inside of
18461902
// `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
18471903
// data via `write_tlv_fields`.

lightning/src/ln/channel.rs

+39-25
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use bitcoin::transaction::{Transaction, TxIn, TxOut};
1414
use bitcoin::sighash::EcdsaSighashType;
1515
use bitcoin::consensus::encode;
1616
use bitcoin::absolute::LockTime;
17-
use bitcoin::Weight;
17+
use bitcoin::{Weight, Witness};
1818

1919
use bitcoin::hashes::Hash;
2020
use bitcoin::hashes::sha256::Hash as Sha256;
@@ -2630,7 +2630,7 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
26302630
},
26312631
};
26322632

2633-
let funding_ready_for_sig_event = if signing_session.local_inputs_count() == 0 {
2633+
let funding_ready_for_sig_event_opt = if signing_session.local_inputs_count() == 0 {
26342634
debug_assert_eq!(our_funding_satoshis, 0);
26352635
if signing_session.provide_holder_witnesses(self.context.channel_id, Vec::new()).is_err() {
26362636
debug_assert!(
@@ -2644,28 +2644,12 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
26442644
}
26452645
None
26462646
} else {
2647-
// TODO(dual_funding): Send event for signing if we've contributed funds.
2648-
// Inform the user that SIGHASH_ALL must be used for all signatures when contributing
2649-
// inputs/signatures.
2650-
// Also warn the user that we don't do anything to prevent the counterparty from
2651-
// providing non-standard witnesses which will prevent the funding transaction from
2652-
// confirming. This warning must appear in doc comments wherever the user is contributing
2653-
// funds, whether they are initiator or acceptor.
2654-
//
2655-
// The following warning can be used when the APIs allowing contributing inputs become available:
2656-
// <div class="warning">
2657-
// WARNING: LDK makes no attempt to prevent the counterparty from using non-standard inputs which
2658-
// will prevent the funding transaction from being relayed on the bitcoin network and hence being
2659-
// confirmed.
2660-
// </div>
2661-
debug_assert!(
2662-
false,
2663-
"We don't support users providing inputs but somehow we had more than zero inputs",
2664-
);
2665-
return Err(ChannelError::Close((
2666-
"V2 channel rejected due to sender error".into(),
2667-
ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(false) }
2668-
)));
2647+
Some(Event::FundingTransactionReadyForSigning {
2648+
channel_id: self.context.channel_id,
2649+
counterparty_node_id: self.context.counterparty_node_id,
2650+
user_channel_id: self.context.user_id,
2651+
unsigned_transaction: signing_session.unsigned_tx().build_unsigned_tx(),
2652+
})
26692653
};
26702654

26712655
let mut channel_state = ChannelState::FundingNegotiated(FundingNegotiatedFlags::new());
@@ -2676,7 +2660,7 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
26762660
self.interactive_tx_constructor.take();
26772661
self.interactive_tx_signing_session = Some(signing_session);
26782662

2679-
Ok((commitment_signed, funding_ready_for_sig_event))
2663+
Ok((commitment_signed, funding_ready_for_sig_event_opt))
26802664
}
26812665
}
26822666

@@ -6565,6 +6549,36 @@ impl<SP: Deref> FundedChannel<SP> where
65656549
}
65666550
}
65676551

6552+
fn verify_interactive_tx_signatures(&mut self, _witnesses: &Vec<Witness>) {
6553+
if let Some(ref mut _signing_session) = self.interactive_tx_signing_session {
6554+
// Check that sighash_all was used:
6555+
// TODO(dual_funding): Check sig for sighash
6556+
}
6557+
}
6558+
6559+
pub fn funding_transaction_signed<L: Deref>(&mut self, witnesses: Vec<Witness>, logger: &L) -> Result<Option<msgs::TxSignatures>, APIError>
6560+
where L::Target: Logger
6561+
{
6562+
self.verify_interactive_tx_signatures(&witnesses);
6563+
if let Some(ref mut signing_session) = self.interactive_tx_signing_session {
6564+
let logger = WithChannelContext::from(logger, &self.context, None);
6565+
if let Some(holder_tx_signatures) = signing_session
6566+
.provide_holder_witnesses(self.context.channel_id, witnesses)
6567+
.map_err(|err| APIError::APIMisuseError { err })?
6568+
{
6569+
if self.is_awaiting_initial_mon_persist() {
6570+
log_debug!(logger, "Not sending tx_signatures: a monitor update is in progress. Setting monitor_pending_tx_signatures.");
6571+
self.context.monitor_pending_tx_signatures = Some(holder_tx_signatures);
6572+
return Ok(None);
6573+
}
6574+
return Ok(Some(holder_tx_signatures));
6575+
} else { return Ok(None) }
6576+
} else {
6577+
return Err(APIError::APIMisuseError {
6578+
err: format!("Channel with id {} not expecting funding signatures", self.context.channel_id)});
6579+
}
6580+
}
6581+
65686582
pub fn tx_signatures<L: Deref>(&mut self, msg: &msgs::TxSignatures, logger: &L) -> Result<(Option<Transaction>, Option<msgs::TxSignatures>), ChannelError>
65696583
where L::Target: Logger
65706584
{

lightning/src/ln/channelmanager.rs

+53
Original file line numberDiff line numberDiff line change
@@ -5511,6 +5511,59 @@ where
55115511
result
55125512
}
55135513

5514+
/// Handles a signed funding transaction generated by interactive transaction construction and
5515+
/// provided by the client.
5516+
///
5517+
/// Do NOT broadcast the funding transaction yourself. When we have safely received our
5518+
/// counterparty's signature(s) the funding transaction will automatically be broadcast via the
5519+
/// [`BroadcasterInterface`] provided when this `ChannelManager` was constructed.
5520+
///
5521+
/// SIGHASH_ALL MUST be used for all signatures when providing signatures.
5522+
///
5523+
/// <div class="warning">
5524+
/// WARNING: LDK makes no attempt to prevent the counterparty from using non-standard inputs which
5525+
/// will prevent the funding transaction from being relayed on the bitcoin network and hence being
5526+
/// confirmed.
5527+
/// </div>
5528+
pub fn funding_transaction_signed(
5529+
&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, transaction: Transaction
5530+
) -> Result<(), APIError> {
5531+
let witnesses: Vec<_> = transaction.input.into_iter().filter_map(|input| {
5532+
if input.witness.is_empty() { None } else { Some(input.witness) }
5533+
}).collect();
5534+
5535+
let per_peer_state = self.per_peer_state.read().unwrap();
5536+
let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5537+
.ok_or_else(|| APIError::ChannelUnavailable {
5538+
err: format!("Can't find a peer matching the passed counterparty node_id {}",
5539+
counterparty_node_id) })?;
5540+
5541+
let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5542+
let peer_state = &mut *peer_state_lock;
5543+
5544+
match peer_state.channel_by_id.get_mut(channel_id) {
5545+
Some(channel) => {
5546+
match channel.as_funded_mut() {
5547+
Some(chan) => {
5548+
if let Some(tx_signatures) = chan.funding_transaction_signed(witnesses, &self.logger)? {
5549+
peer_state.pending_msg_events.push(MessageSendEvent::SendTxSignatures {
5550+
node_id: *counterparty_node_id,
5551+
msg: tx_signatures,
5552+
});
5553+
}
5554+
},
5555+
None => return Err(APIError::APIMisuseError {
5556+
err: format!("Channel with id {} not expecting funding signatures", channel_id)}),
5557+
}
5558+
},
5559+
None => return Err(APIError::ChannelUnavailable{
5560+
err: format!("Channel with id {} not found for the passed counterparty node_id {}", channel_id,
5561+
counterparty_node_id) }),
5562+
}
5563+
5564+
Ok(())
5565+
}
5566+
55145567
/// Atomically applies partial updates to the [`ChannelConfig`] of the given channels.
55155568
///
55165569
/// Once the updates are applied, each eligible channel (advertised with a known short channel

lightning/src/ln/interactivetxs.rs

+12-4
Original file line numberDiff line numberDiff line change
@@ -396,9 +396,13 @@ 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(), local_inputs_count
405+
));
402406
}
403407

404408
self.unsigned_tx.add_local_witnesses(witnesses.clone());
@@ -409,7 +413,11 @@ impl InteractiveTxSigningSession {
409413
shared_input_signature: None,
410414
});
411415

412-
Ok(())
416+
if self.holder_sends_tx_signatures_first && self.has_received_commitment_signed {
417+
Ok(self.holder_tx_signatures.clone())
418+
} else {
419+
Ok(None)
420+
}
413421
}
414422

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

0 commit comments

Comments
 (0)