Skip to content

Commit 2a7d713

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 61e5819 commit 2a7d713

File tree

4 files changed

+262
-91
lines changed

4 files changed

+262
-91
lines changed

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: 54 additions & 78 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,
@@ -2549,7 +2549,6 @@ where
25492549
monitor_pending_failures: Vec<(HTLCSource, PaymentHash, HTLCFailReason)>,
25502550
monitor_pending_finalized_fulfills: Vec<(HTLCSource, Option<AttributionData>)>,
25512551
monitor_pending_update_adds: Vec<msgs::UpdateAddHTLC>,
2552-
monitor_pending_tx_signatures: Option<msgs::TxSignatures>,
25532552

25542553
/// If we went to send a revoke_and_ack but our signer was unable to give us a signature,
25552554
/// we should retry at some point in the future when the signer indicates it may have a
@@ -3269,7 +3268,6 @@ where
32693268
monitor_pending_failures: Vec::new(),
32703269
monitor_pending_finalized_fulfills: Vec::new(),
32713270
monitor_pending_update_adds: Vec::new(),
3272-
monitor_pending_tx_signatures: None,
32733271

32743272
signer_pending_revoke_and_ack: false,
32753273
signer_pending_commitment_update: false,
@@ -3508,7 +3506,6 @@ where
35083506
monitor_pending_failures: Vec::new(),
35093507
monitor_pending_finalized_fulfills: Vec::new(),
35103508
monitor_pending_update_adds: Vec::new(),
3511-
monitor_pending_tx_signatures: None,
35123509

35133510
signer_pending_revoke_and_ack: false,
35143511
signer_pending_commitment_update: false,
@@ -6979,12 +6976,8 @@ where
69796976

69806977
self.monitor_updating_paused(false, false, false, Vec::new(), Vec::new(), Vec::new());
69816978

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);
6979+
if let Some(session) = &mut self.interactive_tx_signing_session {
6980+
session.received_commitment_signed();
69886981
}
69896982

69906983
Ok(channel_monitor)
@@ -7072,13 +7065,11 @@ where
70727065
channel_id: Some(self.context.channel_id()),
70737066
};
70747067

7075-
let tx_signatures = self
7076-
.interactive_tx_signing_session
7068+
self.interactive_tx_signing_session
70777069
.as_mut()
70787070
.expect("Signing session must exist for negotiated pending splice")
70797071
.received_commitment_signed();
70807072
self.monitor_updating_paused(false, false, false, Vec::new(), Vec::new(), Vec::new());
7081-
self.context.monitor_pending_tx_signatures = tx_signatures;
70827073

70837074
Ok(self.push_ret_blockable_mon_update(monitor_update))
70847075
}
@@ -7988,10 +7979,26 @@ where
79887979
}
79897980
}
79907981

7982+
pub fn funding_transaction_signed(
7983+
&mut self, witnesses: Vec<Witness>,
7984+
) -> Result<Option<msgs::TxSignatures>, APIError> {
7985+
self.interactive_tx_signing_session
7986+
.as_mut()
7987+
.ok_or_else(|| APIError::APIMisuseError {
7988+
err: format!(
7989+
"Channel {} not expecting funding signatures",
7990+
self.context.channel_id
7991+
),
7992+
})
7993+
.and_then(|signing_session| {
7994+
signing_session
7995+
.provide_holder_witnesses(self.context.channel_id, witnesses)
7996+
.map_err(|err| APIError::APIMisuseError { err })
7997+
})
7998+
}
7999+
79918000
#[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-
{
8001+
pub fn tx_signatures(&mut self, msg: &msgs::TxSignatures) -> Result<(Option<Transaction>, Option<msgs::TxSignatures>), ChannelError> {
79958002
if !self.context.channel_state.is_interactive_signing()
79968003
|| self.context.channel_state.is_their_tx_signatures_sent()
79978004
{
@@ -8014,23 +8021,12 @@ where
80148021
return Err(ChannelError::Close((msg.to_owned(), reason)));
80158022
}
80168023

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-
80238024
for witness in &msg.witnesses {
80248025
if witness.is_empty() {
80258026
let msg = "Unexpected empty witness in tx_signatures received";
80268027
let reason = ClosureReason::ProcessingError { err: msg.to_owned() };
80278028
return Err(ChannelError::Close((msg.to_owned(), reason)));
80288029
}
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.
80348030
}
80358031

80368032
let (holder_tx_signatures_opt, funding_tx_opt) = signing_session.received_tx_signatures(msg.clone())
@@ -8044,15 +8040,8 @@ where
80448040
self.funding.funding_transaction = funding_tx_opt.clone();
80458041
}
80468042

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-
8043+
// Note that `holder_tx_signatures_opt` will be `None` if we sent `tx_signatures` first or if the
8044+
// user still needs to provide tx_signatures and we are sending second.
80568045
if holder_tx_signatures_opt.is_some() {
80578046
self.context.channel_state.set_our_tx_signatures_ready();
80588047
}
@@ -8309,25 +8298,14 @@ where
83098298
mem::swap(&mut finalized_claimed_htlcs, &mut self.context.monitor_pending_finalized_fulfills);
83108299
let mut pending_update_adds = Vec::new();
83118300
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-
}
83238301

83248302
if self.context.channel_state.is_peer_disconnected() {
83258303
self.context.monitor_pending_revoke_and_ack = false;
83268304
self.context.monitor_pending_commitment_signed = false;
83278305
return MonitorRestoreUpdates {
83288306
raa: None, commitment_update: None, order: RAACommitmentOrder::RevokeAndACKFirst,
83298307
accepted_htlcs, failed_htlcs, finalized_claimed_htlcs, pending_update_adds,
8330-
funding_broadcastable, channel_ready, announcement_sigs, tx_signatures
8308+
funding_broadcastable, channel_ready, announcement_sigs, tx_signatures: None
83318309
};
83328310
}
83338311

@@ -8357,7 +8335,7 @@ where
83578335
match order { RAACommitmentOrder::CommitmentFirst => "commitment", RAACommitmentOrder::RevokeAndACKFirst => "RAA"});
83588336
MonitorRestoreUpdates {
83598337
raa, commitment_update, order, accepted_htlcs, failed_htlcs, finalized_claimed_htlcs,
8360-
pending_update_adds, funding_broadcastable, channel_ready, announcement_sigs, tx_signatures
8338+
pending_update_adds, funding_broadcastable, channel_ready, announcement_sigs, tx_signatures: None
83618339
}
83628340
}
83638341

@@ -8632,23 +8610,25 @@ where
86328610
log_trace!(logger, "Regenerating latest commitment update in channel {} with{} {} update_adds, {} update_fulfills, {} update_fails, and {} update_fail_malformeds",
86338611
&self.context.channel_id(), if update_fee.is_some() { " update_fee," } else { "" },
86348612
update_add_htlcs.len(), update_fulfill_htlcs.len(), update_fail_htlcs.len(), update_fail_malformed_htlcs.len());
8635-
let commitment_signed =
8636-
if let Ok(update) = self.send_commitment_no_state_update(logger) {
8637-
if self.context.signer_pending_commitment_update {
8638-
log_trace!(
8639-
logger,
8640-
"Commitment update generated: clearing signer_pending_commitment_update"
8641-
);
8642-
self.context.signer_pending_commitment_update = false;
8643-
}
8644-
update
8645-
} else {
8646-
if !self.context.signer_pending_commitment_update {
8647-
log_trace!(logger, "Commitment update awaiting signer: setting signer_pending_commitment_update");
8648-
self.context.signer_pending_commitment_update = true;
8649-
}
8650-
return Err(());
8651-
};
8613+
let commitment_signed = if let Ok(update) = self.send_commitment_no_state_update(logger) {
8614+
if self.context.signer_pending_commitment_update {
8615+
log_trace!(
8616+
logger,
8617+
"Commitment update generated: clearing signer_pending_commitment_update"
8618+
);
8619+
self.context.signer_pending_commitment_update = false;
8620+
}
8621+
update
8622+
} else {
8623+
if !self.context.signer_pending_commitment_update {
8624+
log_trace!(
8625+
logger,
8626+
"Commitment update awaiting signer: setting signer_pending_commitment_update"
8627+
);
8628+
self.context.signer_pending_commitment_update = true;
8629+
}
8630+
return Err(());
8631+
};
86528632
Ok(msgs::CommitmentUpdate {
86538633
update_add_htlcs,
86548634
update_fulfill_htlcs,
@@ -8834,7 +8814,6 @@ where
88348814
update_fee: None,
88358815
})
88368816
} else { None };
8837-
// TODO(dual_funding): For async signing support we need to hold back `tx_signatures` until the `commitment_signed` is ready.
88388817
let tx_signatures = if (
88398818
// if it has not received tx_signatures for that funding transaction AND
88408819
// if it has already received commitment_signed AND it should sign first, as specified in the tx_signatures requirements:
@@ -8843,14 +8822,8 @@ where
88438822
// else if it has already received tx_signatures for that funding transaction:
88448823
// MUST send its tx_signatures for that funding transaction.
88458824
) || 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-
}
8825+
if session.holder_tx_signatures().is_none() {
8826+
log_debug!(logger, "Not sending tx_signatures: a monitor update is in progress.");
88548827
None
88558828
} else {
88568829
// If `holder_tx_signatures` is `None` here, the `tx_signatures` message will be sent
@@ -11792,6 +11765,10 @@ where
1179211765
// CHANNEL_ANNOUNCEMENT_PROPAGATION_DELAY confirmations.
1179311766
self.context.historical_scids.drain(0..end)
1179411767
}
11768+
11769+
pub fn set_our_tx_signatures_ready(&mut self) {
11770+
self.context.channel_state.set_our_tx_signatures_ready();
11771+
}
1179511772
}
1179611773

1179711774
/// A not-yet-funded outbound (from holder) channel using V1 channel establishment.
@@ -13956,7 +13933,6 @@ where
1395613933
monitor_pending_failures,
1395713934
monitor_pending_finalized_fulfills: monitor_pending_finalized_fulfills.unwrap(),
1395813935
monitor_pending_update_adds: monitor_pending_update_adds.unwrap_or_default(),
13959-
monitor_pending_tx_signatures: None,
1396013936

1396113937
signer_pending_revoke_and_ack: false,
1396213938
signer_pending_commitment_update: false,

0 commit comments

Comments
 (0)