Skip to content

Commit d78778f

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 b3c4f18 commit d78778f

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
@@ -1541,7 +1541,56 @@ pub enum Event {
15411541
/// The node id of the peer we just connected to, who advertises support for
15421542
/// onion messages.
15431543
peer_node_id: PublicKey,
1544-
}
1544+
},
1545+
/// Indicates that a funding transaction constructed via interactive transaction construction for a
1546+
/// channel is ready to be signed by the client. This event will only be triggered
1547+
/// if at least one input was contributed by the holder and needs to be signed.
1548+
///
1549+
/// The transaction contains all inputs provided by both parties along with the channel's funding
1550+
/// output and a change output if applicable.
1551+
///
1552+
/// No part of the transaction should be changed before signing as the content of the transaction
1553+
/// has already been negotiated with the counterparty.
1554+
///
1555+
/// Each signature MUST use the SIGHASH_ALL flag to avoid invalidation of the initial commitment and
1556+
/// hence possible loss of funds.
1557+
///
1558+
/// After signing, call [`ChannelManager::funding_transaction_signed`] with the (partially) signed
1559+
/// funding transaction.
1560+
///
1561+
/// Generated in [`ChannelManager`] message handling.
1562+
///
1563+
/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
1564+
/// [`ChannelManager::funding_transaction_signed`]: crate::ln::channelmanager::ChannelManager::funding_transaction_signed
1565+
FundingTransactionReadyForSigning {
1566+
/// The channel_id of the channel which you'll need to pass back into
1567+
/// [`ChannelManager::funding_transaction_signed`].
1568+
///
1569+
/// [`ChannelManager::funding_transaction_signed`]: crate::ln::channelmanager::ChannelManager::funding_transaction_signed
1570+
channel_id: ChannelId,
1571+
/// The counterparty's node_id, which you'll need to pass back into
1572+
/// [`ChannelManager::funding_transaction_signed`].
1573+
///
1574+
/// [`ChannelManager::funding_transaction_signed`]: crate::ln::channelmanager::ChannelManager::funding_transaction_signed
1575+
counterparty_node_id: PublicKey,
1576+
// TODO(dual_funding): Enable links when methods are implemented
1577+
/// The `user_channel_id` value passed in to `ChannelManager::create_dual_funded_channel` for outbound
1578+
/// channels, or to [`ChannelManager::accept_inbound_channel`] or `ChannelManager::accept_inbound_channel_with_contribution`
1579+
/// for inbound channels if [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
1580+
/// Otherwise `user_channel_id` will be randomized for an inbound channel.
1581+
/// This may be zero for objects serialized with LDK versions prior to 0.0.113.
1582+
///
1583+
/// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1584+
/// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1585+
// [`ChannelManager::create_dual_funded_channel`]: crate::ln::channelmanager::ChannelManager::create_dual_funded_channel
1586+
// [`ChannelManager::accept_inbound_channel_with_contribution`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel_with_contribution
1587+
user_channel_id: u128,
1588+
/// The unsigned transaction to be signed and passed back to
1589+
/// [`ChannelManager::funding_transaction_signed`].
1590+
///
1591+
/// [`ChannelManager::funding_transaction_signed`]: crate::ln::channelmanager::ChannelManager::funding_transaction_signed
1592+
unsigned_transaction: Transaction,
1593+
},
15451594
}
15461595

15471596
impl Writeable for Event {
@@ -1887,6 +1936,13 @@ impl Writeable for Event {
18871936
(8, former_temporary_channel_id, required),
18881937
});
18891938
},
1939+
&Event::FundingTransactionReadyForSigning { .. } => {
1940+
45u8.write(writer)?;
1941+
// We never write out FundingTransactionReadyForSigning events as, upon disconnection, peers
1942+
// drop any V2-established/spliced channels which have not yet exchanged the initial `commitment_signed`.
1943+
// We only exhange the initial `commitment_signed` after the client calls
1944+
// `ChannelManager::funding_transaction_signed` and ALWAYS before we send a `tx_signatures`
1945+
},
18901946
// Note that, going forward, all new events must only write data inside of
18911947
// `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
18921948
// 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

@@ -6595,6 +6579,36 @@ impl<SP: Deref> FundedChannel<SP> where
65956579
}
65966580
}
65976581

6582+
fn verify_interactive_tx_signatures(&mut self, _witnesses: &Vec<Witness>) {
6583+
if let Some(ref mut _signing_session) = self.interactive_tx_signing_session {
6584+
// Check that sighash_all was used:
6585+
// TODO(dual_funding): Check sig for sighash
6586+
}
6587+
}
6588+
6589+
pub fn funding_transaction_signed<L: Deref>(&mut self, witnesses: Vec<Witness>, logger: &L) -> Result<Option<msgs::TxSignatures>, APIError>
6590+
where L::Target: Logger
6591+
{
6592+
self.verify_interactive_tx_signatures(&witnesses);
6593+
if let Some(ref mut signing_session) = self.interactive_tx_signing_session {
6594+
let logger = WithChannelContext::from(logger, &self.context, None);
6595+
if let Some(holder_tx_signatures) = signing_session
6596+
.provide_holder_witnesses(self.context.channel_id, witnesses)
6597+
.map_err(|err| APIError::APIMisuseError { err })?
6598+
{
6599+
if self.is_awaiting_initial_mon_persist() {
6600+
log_debug!(logger, "Not sending tx_signatures: a monitor update is in progress. Setting monitor_pending_tx_signatures.");
6601+
self.context.monitor_pending_tx_signatures = Some(holder_tx_signatures);
6602+
return Ok(None);
6603+
}
6604+
return Ok(Some(holder_tx_signatures));
6605+
} else { return Ok(None) }
6606+
} else {
6607+
return Err(APIError::APIMisuseError {
6608+
err: format!("Channel with id {} not expecting funding signatures", self.context.channel_id)});
6609+
}
6610+
}
6611+
65986612
pub fn tx_signatures<L: Deref>(&mut self, msg: &msgs::TxSignatures, logger: &L) -> Result<(Option<Transaction>, Option<msgs::TxSignatures>), ChannelError>
65996613
where L::Target: Logger
66006614
{

lightning/src/ln/channelmanager.rs

+53
Original file line numberDiff line numberDiff line change
@@ -5514,6 +5514,59 @@ where
55145514
result
55155515
}
55165516

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