Skip to content

Commit 8f204b0

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 e01663a commit 8f204b0

4 files changed

Lines changed: 273 additions & 90 deletions

File tree

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 and outputs provided by both parties including the
1699+
/// channel's funding 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 {
@@ -2134,6 +2180,11 @@ impl Writeable for Event {
21342180
47u8.write(writer)?;
21352181
// Never write StaticInvoiceRequested events as buffered onion messages aren't serialized.
21362182
},
2183+
&Event::FundingTransactionReadyForSigning { .. } => {
2184+
49u8.write(writer)?;
2185+
// We never write out FundingTransactionReadyForSigning events as they will be regenerated when
2186+
// necessary.
2187+
},
21372188
// Note that, going forward, all new events must only write data inside of
21382189
// `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
21392190
// data via `write_tlv_fields`.
@@ -2716,6 +2767,8 @@ impl MaybeReadable for Event {
27162767
// Note that we do not write a length-prefixed TLV for StaticInvoiceRequested events.
27172768
#[cfg(async_payments)]
27182769
47u8 => Ok(None),
2770+
// Note that we do not write a length-prefixed TLV for FundingTransactionReadyForSigning events.
2771+
49u8 => Ok(None),
27192772
// Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
27202773
// Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
27212774
// reads.

lightning/src/ln/channel.rs

Lines changed: 50 additions & 77 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;
@@ -24,9 +24,9 @@ use bitcoin::hashes::Hash;
2424
use bitcoin::secp256k1::constants::PUBLIC_KEY_SIZE;
2525
use bitcoin::secp256k1::{ecdsa::Signature, Secp256k1};
2626
use bitcoin::secp256k1::{PublicKey, SecretKey};
27-
use bitcoin::{secp256k1, sighash};
2827
#[cfg(splicing)]
29-
use bitcoin::{Sequence, Witness};
28+
use bitcoin::Sequence;
29+
use bitcoin::{secp256k1, sighash};
3030

3131
use crate::chain::chaininterface::{
3232
fee_for_weight, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator,
@@ -2181,6 +2181,11 @@ impl FundingScope {
21812181
self.channel_transaction_parameters.is_outbound_from_holder
21822182
}
21832183

2184+
/// Returns a reference to the funding_transaction
2185+
pub fn get_funding_transaction(&self) -> &Option<Transaction> {
2186+
&self.funding_transaction
2187+
}
2188+
21842189
/// Returns the funding_txo we either got from our peer, or were given by
21852190
/// get_funding_created.
21862191
pub fn get_funding_txo(&self) -> Option<OutPoint> {
@@ -2549,7 +2554,6 @@ where
25492554
monitor_pending_failures: Vec<(HTLCSource, PaymentHash, HTLCFailReason)>,
25502555
monitor_pending_finalized_fulfills: Vec<(HTLCSource, Option<AttributionData>)>,
25512556
monitor_pending_update_adds: Vec<msgs::UpdateAddHTLC>,
2552-
monitor_pending_tx_signatures: Option<msgs::TxSignatures>,
25532557

25542558
/// If we went to send a revoke_and_ack but our signer was unable to give us a signature,
25552559
/// we should retry at some point in the future when the signer indicates it may have a
@@ -3269,7 +3273,6 @@ where
32693273
monitor_pending_failures: Vec::new(),
32703274
monitor_pending_finalized_fulfills: Vec::new(),
32713275
monitor_pending_update_adds: Vec::new(),
3272-
monitor_pending_tx_signatures: None,
32733276

32743277
signer_pending_revoke_and_ack: false,
32753278
signer_pending_commitment_update: false,
@@ -3508,7 +3511,6 @@ where
35083511
monitor_pending_failures: Vec::new(),
35093512
monitor_pending_finalized_fulfills: Vec::new(),
35103513
monitor_pending_update_adds: Vec::new(),
3511-
monitor_pending_tx_signatures: None,
35123514

35133515
signer_pending_revoke_and_ack: false,
35143516
signer_pending_commitment_update: false,
@@ -5544,16 +5546,6 @@ where
55445546
};
55455547

55465548
let funding_ready_for_sig_event = if signing_session.local_inputs_count() == 0 {
5547-
if signing_session.provide_holder_witnesses(self.channel_id, Vec::new()).is_err() {
5548-
debug_assert!(
5549-
false,
5550-
"Zero inputs were provided & zero witnesses were provided, but a count mismatch was somehow found",
5551-
);
5552-
return Err(msgs::TxAbort {
5553-
channel_id: self.channel_id(),
5554-
data: "V2 channel rejected due to sender error".to_owned().into_bytes(),
5555-
});
5556-
}
55575549
None
55585550
} else {
55595551
// TODO(dual_funding): Send event for signing if we've contributed funds.
@@ -6978,15 +6970,7 @@ where
69786970
log_info!(logger, "Received initial commitment_signed from peer for channel {}", &self.context.channel_id());
69796971

69806972
self.monitor_updating_paused(false, false, false, Vec::new(), Vec::new(), Vec::new());
6981-
6982-
if let Some(tx_signatures) = self.interactive_tx_signing_session.as_mut().and_then(
6983-
|session| session.received_commitment_signed()
6984-
) {
6985-
// We're up first for submitting our tx_signatures, but our monitor has not persisted yet
6986-
// so they'll be sent as soon as that's done.
6987-
self.context.monitor_pending_tx_signatures = Some(tx_signatures);
6988-
}
6989-
6973+
self.interactive_tx_signing_session.as_mut().expect("signing session should be present").received_commitment_signed();
69906974
Ok(channel_monitor)
69916975
}
69926976

@@ -7072,13 +7056,11 @@ where
70727056
channel_id: Some(self.context.channel_id()),
70737057
};
70747058

7075-
let tx_signatures = self
7076-
.interactive_tx_signing_session
7059+
self.interactive_tx_signing_session
70777060
.as_mut()
70787061
.expect("Signing session must exist for negotiated pending splice")
70797062
.received_commitment_signed();
70807063
self.monitor_updating_paused(false, false, false, Vec::new(), Vec::new(), Vec::new());
7081-
self.context.monitor_pending_tx_signatures = tx_signatures;
70827064

70837065
Ok(self.push_ret_blockable_mon_update(monitor_update))
70847066
}
@@ -7988,10 +7970,39 @@ where
79887970
}
79897971
}
79907972

7973+
pub fn funding_transaction_signed(
7974+
&mut self, witnesses: Vec<Witness>,
7975+
) -> Result<Option<msgs::TxSignatures>, APIError> {
7976+
let (funding_tx_opt, tx_signatures_opt) = self
7977+
.interactive_tx_signing_session
7978+
.as_mut()
7979+
.ok_or_else(|| APIError::APIMisuseError {
7980+
err: format!(
7981+
"Channel {} not expecting funding signatures",
7982+
self.context.channel_id
7983+
),
7984+
})
7985+
.and_then(|signing_session| {
7986+
signing_session
7987+
.provide_holder_witnesses(self.context.channel_id, witnesses)
7988+
.map_err(|err| APIError::APIMisuseError { err })
7989+
})?;
7990+
7991+
if tx_signatures_opt.is_some() {
7992+
self.context.channel_state.set_our_tx_signatures_ready();
7993+
}
7994+
7995+
if funding_tx_opt.is_some() {
7996+
self.funding.funding_transaction = funding_tx_opt;
7997+
self.context.channel_state =
7998+
ChannelState::AwaitingChannelReady(AwaitingChannelReadyFlags::new());
7999+
}
8000+
8001+
Ok(tx_signatures_opt)
8002+
}
8003+
79918004
#[rustfmt::skip]
7992-
pub fn tx_signatures<L: Deref>(&mut self, msg: &msgs::TxSignatures, logger: &L) -> Result<(Option<Transaction>, Option<msgs::TxSignatures>), ChannelError>
7993-
where L::Target: Logger
7994-
{
8005+
pub fn tx_signatures(&mut self, msg: &msgs::TxSignatures) -> Result<(Option<Transaction>, Option<msgs::TxSignatures>), ChannelError> {
79958006
if !self.context.channel_state.is_interactive_signing()
79968007
|| self.context.channel_state.is_their_tx_signatures_sent()
79978008
{
@@ -8014,23 +8025,12 @@ where
80148025
return Err(ChannelError::Close((msg.to_owned(), reason)));
80158026
}
80168027

8017-
if msg.witnesses.len() != signing_session.remote_inputs_count() {
8018-
return Err(ChannelError::Warn(
8019-
"Witness count did not match contributed input count".to_string()
8020-
));
8021-
}
8022-
80238028
for witness in &msg.witnesses {
80248029
if witness.is_empty() {
80258030
let msg = "Unexpected empty witness in tx_signatures received";
80268031
let reason = ClosureReason::ProcessingError { err: msg.to_owned() };
80278032
return Err(ChannelError::Close((msg.to_owned(), reason)));
80288033
}
8029-
8030-
// TODO(dual_funding): Check all sigs are SIGHASH_ALL.
8031-
8032-
// TODO(dual_funding): I don't see how we're going to be able to ensure witness-standardness
8033-
// for spending. Doesn't seem to be anything in rust-bitcoin.
80348034
}
80358035

80368036
let (holder_tx_signatures_opt, funding_tx_opt) = signing_session.received_tx_signatures(msg.clone())
@@ -8040,24 +8040,16 @@ where
80408040
self.context.channel_state.set_their_tx_signatures_sent();
80418041

80428042
if funding_tx_opt.is_some() {
8043+
// TODO(splicing): Transition back to `ChannelReady` and not `AwaitingChannelReady`
80438044
// We have a finalized funding transaction, so we can set the funding transaction.
80448045
self.funding.funding_transaction = funding_tx_opt.clone();
8046+
self.context.channel_state = ChannelState::AwaitingChannelReady(AwaitingChannelReadyFlags::new());
80458047
}
80468048

8047-
// Note that `holder_tx_signatures_opt` will be `None` if we sent `tx_signatures` first, so this
8048-
// case checks if there is a monitor persist in progress when we need to respond with our `tx_signatures`
8049-
// and sets it as pending.
8050-
if holder_tx_signatures_opt.is_some() && self.is_awaiting_initial_mon_persist() {
8051-
log_debug!(logger, "Not sending tx_signatures: a monitor update is in progress. Setting monitor_pending_tx_signatures.");
8052-
self.context.monitor_pending_tx_signatures = holder_tx_signatures_opt;
8053-
return Ok((None, None));
8054-
}
8055-
8056-
if holder_tx_signatures_opt.is_some() {
8057-
self.context.channel_state.set_our_tx_signatures_ready();
8049+
if holder_tx_signatures_opt.is_none() {
8050+
return Ok((funding_tx_opt, None));
80588051
}
80598052

8060-
self.context.channel_state = ChannelState::AwaitingChannelReady(AwaitingChannelReadyFlags::new());
80618053
Ok((funding_tx_opt, holder_tx_signatures_opt))
80628054
} else {
80638055
let msg = "Unexpected tx_signatures. No funding transaction awaiting signatures";
@@ -8309,25 +8301,14 @@ where
83098301
mem::swap(&mut finalized_claimed_htlcs, &mut self.context.monitor_pending_finalized_fulfills);
83108302
let mut pending_update_adds = Vec::new();
83118303
mem::swap(&mut pending_update_adds, &mut self.context.monitor_pending_update_adds);
8312-
// For channels established with V2 establishment we won't send a `tx_signatures` when we're in
8313-
// MonitorUpdateInProgress (and we assume the user will never directly broadcast the funding
8314-
// transaction and waits for us to do it).
8315-
let tx_signatures = self.context.monitor_pending_tx_signatures.take();
8316-
if tx_signatures.is_some() {
8317-
if self.context.channel_state.is_their_tx_signatures_sent() {
8318-
self.context.channel_state = ChannelState::AwaitingChannelReady(AwaitingChannelReadyFlags::new());
8319-
} else {
8320-
self.context.channel_state.set_our_tx_signatures_ready();
8321-
}
8322-
}
83238304

83248305
if self.context.channel_state.is_peer_disconnected() {
83258306
self.context.monitor_pending_revoke_and_ack = false;
83268307
self.context.monitor_pending_commitment_signed = false;
83278308
return MonitorRestoreUpdates {
83288309
raa: None, commitment_update: None, order: RAACommitmentOrder::RevokeAndACKFirst,
83298310
accepted_htlcs, failed_htlcs, finalized_claimed_htlcs, pending_update_adds,
8330-
funding_broadcastable, channel_ready, announcement_sigs, tx_signatures
8311+
funding_broadcastable, channel_ready, announcement_sigs, tx_signatures: None
83318312
};
83328313
}
83338314

@@ -8357,7 +8338,7 @@ where
83578338
match order { RAACommitmentOrder::CommitmentFirst => "commitment", RAACommitmentOrder::RevokeAndACKFirst => "RAA"});
83588339
MonitorRestoreUpdates {
83598340
raa, commitment_update, order, accepted_htlcs, failed_htlcs, finalized_claimed_htlcs,
8360-
pending_update_adds, funding_broadcastable, channel_ready, announcement_sigs, tx_signatures
8341+
pending_update_adds, funding_broadcastable, channel_ready, announcement_sigs, tx_signatures: None
83618342
}
83628343
}
83638344

@@ -8834,7 +8815,6 @@ where
88348815
update_fee: None,
88358816
})
88368817
} else { None };
8837-
// TODO(dual_funding): For async signing support we need to hold back `tx_signatures` until the `commitment_signed` is ready.
88388818
let tx_signatures = if (
88398819
// if it has not received tx_signatures for that funding transaction AND
88408820
// if it has already received commitment_signed AND it should sign first, as specified in the tx_signatures requirements:
@@ -8843,14 +8823,8 @@ where
88438823
// else if it has already received tx_signatures for that funding transaction:
88448824
// MUST send its tx_signatures for that funding transaction.
88458825
) || self.context.channel_state.is_their_tx_signatures_sent() {
8846-
if self.context.channel_state.is_monitor_update_in_progress() {
8847-
// The `monitor_pending_tx_signatures` field should have already been set in `commitment_signed_initial_v2`
8848-
// if we were up first for signing and had a monitor update in progress, but check again just in case.
8849-
debug_assert!(self.context.monitor_pending_tx_signatures.is_some(), "monitor_pending_tx_signatures should already be set");
8850-
log_debug!(logger, "Not sending tx_signatures: a monitor update is in progress. Setting monitor_pending_tx_signatures.");
8851-
if self.context.monitor_pending_tx_signatures.is_none() {
8852-
self.context.monitor_pending_tx_signatures = session.holder_tx_signatures().clone();
8853-
}
8826+
if session.holder_tx_signatures().is_none() {
8827+
log_debug!(logger, "Waiting for funding transaction signatures to be provided");
88548828
None
88558829
} else {
88568830
// If `holder_tx_signatures` is `None` here, the `tx_signatures` message will be sent
@@ -13956,7 +13930,6 @@ where
1395613930
monitor_pending_failures,
1395713931
monitor_pending_finalized_fulfills: monitor_pending_finalized_fulfills.unwrap(),
1395813932
monitor_pending_update_adds: monitor_pending_update_adds.unwrap_or_default(),
13959-
monitor_pending_tx_signatures: None,
1396013933

1396113934
signer_pending_revoke_and_ack: false,
1396213935
signer_pending_commitment_update: false,

0 commit comments

Comments
 (0)