Skip to content

Commit c79b49d

Browse files
committed
Handle re-establishment next_funding_txid
1 parent 982e25d commit c79b49d

File tree

2 files changed

+104
-25
lines changed

2 files changed

+104
-25
lines changed

lightning/src/ln/channel.rs

Lines changed: 87 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,9 @@ use crate::ln::types::ChannelId;
3131
use crate::types::payment::{PaymentPreimage, PaymentHash};
3232
use crate::types::features::{ChannelTypeFeatures, InitFeatures};
3333
use crate::ln::interactivetxs::{
34-
get_output_weight, HandleTxCompleteResult, InteractiveTxConstructor, InteractiveTxConstructorArgs,
35-
InteractiveTxSigningSession, InteractiveTxMessageSendResult, TX_COMMON_FIELDS_WEIGHT,
34+
get_output_weight, HandleTxCompleteValue, HandleTxCompleteResult, InteractiveTxConstructor,
35+
InteractiveTxConstructorArgs, InteractiveTxSigningSession, InteractiveTxMessageSendResult,
36+
TX_COMMON_FIELDS_WEIGHT,
3637
};
3738
use crate::ln::msgs;
3839
use crate::ln::msgs::{ClosingSigned, ClosingSignedFeeRange, DecodeError};
@@ -901,6 +902,7 @@ pub(super) struct MonitorRestoreUpdates {
901902
pub funding_broadcastable: Option<Transaction>,
902903
pub channel_ready: Option<msgs::ChannelReady>,
903904
pub announcement_sigs: Option<msgs::AnnouncementSignatures>,
905+
pub tx_signatures: Option<msgs::TxSignatures>,
904906
}
905907

906908
/// The return value of `signer_maybe_unblocked`
@@ -1252,6 +1254,7 @@ pub(super) struct ChannelContext<SP: Deref> where SP::Target: SignerProvider {
12521254
monitor_pending_failures: Vec<(HTLCSource, PaymentHash, HTLCFailReason)>,
12531255
monitor_pending_finalized_fulfills: Vec<HTLCSource>,
12541256
monitor_pending_update_adds: Vec<msgs::UpdateAddHTLC>,
1257+
monitor_pending_tx_signatures: Option<msgs::TxSignatures>,
12551258

12561259
/// If we went to send a revoke_and_ack but our signer was unable to give us a signature,
12571260
/// we should retry at some point in the future when the signer indicates it may have a
@@ -1494,6 +1497,21 @@ pub(super) struct ChannelContext<SP: Deref> where SP::Target: SignerProvider {
14941497
/// If we can't release a [`ChannelMonitorUpdate`] until some external action completes, we
14951498
/// store it here and only release it to the `ChannelManager` once it asks for it.
14961499
blocked_monitor_updates: Vec<PendingChannelMonitorUpdate>,
1500+
// The `next_funding_txid` field allows peers to finalize the signing steps of an interactive
1501+
// transaction construction, or safely abort that transaction if it was not signed by one of the
1502+
// peers, who has thus already removed it from its state.
1503+
//
1504+
// If we've sent `commtiment_signed` for an interactively constructed transaction
1505+
// during a signing session, but have not received `tx_signatures` we MUST set `next_funding_txid`
1506+
// to the txid of that interactive transaction, else we MUST NOT set it.
1507+
//
1508+
// See the spec for further details on this:
1509+
// * `channel_reestablish`-sending node: https://github.com/lightning/bolts/blob/247e83d/02-peer-protocol.md?plain=1#L2466-L2470
1510+
// * `channel_reestablish`-receiving node: https://github.com/lightning/bolts/blob/247e83d/02-peer-protocol.md?plain=1#L2520-L2531
1511+
//
1512+
// TODO(dual_funding): Persist this when we actually contribute funding inputs. For now we always
1513+
// send an empty witnesses array in `tx_signatures` as a V2 channel acceptor
1514+
next_funding_txid: Option<Txid>,
14971515
}
14981516

14991517
/// A channel struct implementing this trait can receive an initial counterparty commitment
@@ -1710,14 +1728,29 @@ pub(super) trait InteractivelyFunded<SP: Deref> where SP::Target: SignerProvider
17101728
}
17111729

17121730
fn tx_complete(&mut self, msg: &msgs::TxComplete) -> HandleTxCompleteResult {
1713-
HandleTxCompleteResult(match self.interactive_tx_constructor_mut() {
1714-
Some(ref mut tx_constructor) => tx_constructor.handle_tx_complete(msg).map_err(
1715-
|reason| reason.into_tx_abort_msg(self.context().channel_id())),
1716-
None => Err(msgs::TxAbort {
1717-
channel_id: self.context().channel_id(),
1718-
data: b"No interactive transaction negotiation in progress".to_vec()
1719-
}),
1720-
})
1731+
let tx_constructor = match self.interactive_tx_constructor_mut() {
1732+
Some(ref mut tx_constructor) => tx_constructor,
1733+
None => {
1734+
let tx_abort = msgs::TxAbort {
1735+
channel_id: msg.channel_id,
1736+
data: b"No interactive transaction negotiation in progress".to_vec(),
1737+
};
1738+
return HandleTxCompleteResult(Err(tx_abort));
1739+
},
1740+
};
1741+
1742+
let tx_complete = match tx_constructor.handle_tx_complete(msg) {
1743+
Ok(tx_complete) => tx_complete,
1744+
Err(reason) => {
1745+
return HandleTxCompleteResult(Err(reason.into_tx_abort_msg(msg.channel_id)))
1746+
}
1747+
};
1748+
1749+
if let HandleTxCompleteValue::SendTxComplete(_, ref signing_session) = tx_complete {
1750+
self.context_mut().next_funding_txid = Some(signing_session.unsigned_tx.compute_txid());
1751+
};
1752+
1753+
HandleTxCompleteResult(Ok(tx_complete))
17211754
}
17221755

17231756
fn funding_tx_constructed<L: Deref>(
@@ -2077,6 +2110,7 @@ impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
20772110
monitor_pending_failures: Vec::new(),
20782111
monitor_pending_finalized_fulfills: Vec::new(),
20792112
monitor_pending_update_adds: Vec::new(),
2113+
monitor_pending_tx_signatures: None,
20802114

20812115
signer_pending_revoke_and_ack: false,
20822116
signer_pending_commitment_update: false,
@@ -2170,6 +2204,8 @@ impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
21702204
blocked_monitor_updates: Vec::new(),
21712205

21722206
is_manual_broadcast: false,
2207+
2208+
next_funding_txid: None,
21732209
};
21742210

21752211
Ok(channel_context)
@@ -2311,6 +2347,7 @@ impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
23112347
monitor_pending_failures: Vec::new(),
23122348
monitor_pending_finalized_fulfills: Vec::new(),
23132349
monitor_pending_update_adds: Vec::new(),
2350+
monitor_pending_tx_signatures: None,
23142351

23152352
signer_pending_revoke_and_ack: false,
23162353
signer_pending_commitment_update: false,
@@ -2401,6 +2438,7 @@ impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
24012438
blocked_monitor_updates: Vec::new(),
24022439
local_initiated_shutdown: None,
24032440
is_manual_broadcast: false,
2441+
next_funding_txid: None,
24042442
})
24052443
}
24062444

@@ -4955,6 +4993,14 @@ impl<SP: Deref> Channel<SP> where
49554993
self.context.channel_state = ChannelState::AwaitingChannelReady(AwaitingChannelReadyFlags::new());
49564994
self.monitor_updating_paused(false, false, need_channel_ready, Vec::new(), Vec::new(), Vec::new());
49574995

4996+
if let Some(tx_signatures) = self.interactive_tx_signing_session.as_mut().and_then(
4997+
|session| session.received_commitment_signed()
4998+
) {
4999+
// We're up first for submitting our tx_signatures, but our monitor has not persisted yet
5000+
// so they'll be sent as soon as that's done.
5001+
self.context.monitor_pending_tx_signatures = Some(tx_signatures);
5002+
}
5003+
49585004
Ok(channel_monitor)
49595005
}
49605006

@@ -5628,7 +5674,13 @@ impl<SP: Deref> Channel<SP> where
56285674
}
56295675
}
56305676

5631-
pub fn tx_signatures(&mut self, msg: &msgs::TxSignatures) -> Result<(Option<msgs::TxSignatures>, Option<Transaction>), ChannelError> {
5677+
pub fn tx_signatures<L: Deref>(&mut self, msg: &msgs::TxSignatures, logger: &L) -> Result<(Option<msgs::TxSignatures>, Option<Transaction>), ChannelError>
5678+
where L::Target: Logger
5679+
{
5680+
if !matches!(self.context.channel_state, ChannelState::FundingNegotiated) {
5681+
return Err(ChannelError::close("Received tx_signatures in strange state!".to_owned()));
5682+
}
5683+
56325684
if let Some(ref mut signing_session) = self.interactive_tx_signing_session {
56335685
if msg.witnesses.len() != signing_session.remote_inputs_count() {
56345686
return Err(ChannelError::Warn(
@@ -5666,9 +5718,17 @@ impl<SP: Deref> Channel<SP> where
56665718
}
56675719
self.context.funding_transaction = funding_tx_opt.clone();
56685720

5721+
self.context.next_funding_txid = None;
5722+
56695723
// Clear out the signing session
56705724
self.interactive_tx_signing_session = None;
56715725

5726+
if tx_signatures_opt.is_some() && self.context.channel_state.is_monitor_update_in_progress() {
5727+
log_debug!(logger, "Not sending tx_signatures: a monitor update is in progress. Setting monitor_pending_tx_signatures.");
5728+
self.context.monitor_pending_tx_signatures = tx_signatures_opt;
5729+
return Ok((None, None));
5730+
}
5731+
56725732
Ok((tx_signatures_opt, funding_tx_opt))
56735733
} else {
56745734
Err(ChannelError::Close((
@@ -5911,14 +5971,18 @@ impl<SP: Deref> Channel<SP> where
59115971
mem::swap(&mut finalized_claimed_htlcs, &mut self.context.monitor_pending_finalized_fulfills);
59125972
let mut pending_update_adds = Vec::new();
59135973
mem::swap(&mut pending_update_adds, &mut self.context.monitor_pending_update_adds);
5974+
// For channels established with V2 establishment we won't send a `tx_signatures` when we're in
5975+
// MonitorUpdateInProgress (and we assume the user will never directly broadcast the funding
5976+
// transaction and waits for us to do it).
5977+
let tx_signatures = self.context.monitor_pending_tx_signatures.take();
59145978

59155979
if self.context.channel_state.is_peer_disconnected() {
59165980
self.context.monitor_pending_revoke_and_ack = false;
59175981
self.context.monitor_pending_commitment_signed = false;
59185982
return MonitorRestoreUpdates {
59195983
raa: None, commitment_update: None, order: RAACommitmentOrder::RevokeAndACKFirst,
59205984
accepted_htlcs, failed_htlcs, finalized_claimed_htlcs, pending_update_adds,
5921-
funding_broadcastable, channel_ready, announcement_sigs
5985+
funding_broadcastable, channel_ready, announcement_sigs, tx_signatures
59225986
};
59235987
}
59245988

@@ -5952,7 +6016,7 @@ impl<SP: Deref> Channel<SP> where
59526016
match order { RAACommitmentOrder::CommitmentFirst => "commitment", RAACommitmentOrder::RevokeAndACKFirst => "RAA"});
59536017
MonitorRestoreUpdates {
59546018
raa, commitment_update, order, accepted_htlcs, failed_htlcs, finalized_claimed_htlcs,
5955-
pending_update_adds, funding_broadcastable, channel_ready, announcement_sigs
6019+
pending_update_adds, funding_broadcastable, channel_ready, announcement_sigs, tx_signatures
59566020
}
59576021
}
59586022

@@ -7723,10 +7787,7 @@ impl<SP: Deref> Channel<SP> where
77237787
next_remote_commitment_number: INITIAL_COMMITMENT_NUMBER - self.context.cur_counterparty_commitment_transaction_number - 1,
77247788
your_last_per_commitment_secret: remote_last_secret,
77257789
my_current_per_commitment_point: dummy_pubkey,
7726-
// TODO(dual_funding): If we've sent `commtiment_signed` for an interactive transaction
7727-
// construction but have not received `tx_signatures` we MUST set `next_funding_txid` to the
7728-
// txid of that interactive transaction, else we MUST NOT set it.
7729-
next_funding_txid: None,
7790+
next_funding_txid: self.context.next_funding_txid,
77307791
}
77317792
}
77327793

@@ -9427,7 +9488,8 @@ impl<SP: Deref> Writeable for Channel<SP> where SP::Target: SignerProvider {
94279488
(47, next_holder_commitment_point, option),
94289489
(49, self.context.local_initiated_shutdown, option), // Added in 0.0.122
94299490
(51, is_manual_broadcast, option), // Added in 0.0.124
9430-
(53, funding_tx_broadcast_safe_event_emitted, option) // Added in 0.0.124
9491+
(53, funding_tx_broadcast_safe_event_emitted, option), // Added in 0.0.124
9492+
(55, self.context.next_funding_txid, option) // Added in 0.1.0
94319493
});
94329494

94339495
Ok(())
@@ -9717,6 +9779,7 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, u32, &'c Ch
97179779
let mut channel_pending_event_emitted = None;
97189780
let mut channel_ready_event_emitted = None;
97199781
let mut funding_tx_broadcast_safe_event_emitted = None;
9782+
let mut next_funding_txid = funding_transaction.as_ref().map(|tx| tx.compute_txid());
97209783

97219784
let mut user_id_high_opt: Option<u64> = None;
97229785
let mut channel_keys_id: Option<[u8; 32]> = None;
@@ -9777,6 +9840,7 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, u32, &'c Ch
97779840
(49, local_initiated_shutdown, option),
97789841
(51, is_manual_broadcast, option),
97799842
(53, funding_tx_broadcast_safe_event_emitted, option),
9843+
(55, next_funding_txid, option) // Added in 0.0.125
97809844
});
97819845

97829846
let (channel_keys_id, holder_signer) = if let Some(channel_keys_id) = channel_keys_id {
@@ -9950,6 +10014,7 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, u32, &'c Ch
995010014
monitor_pending_failures,
995110015
monitor_pending_finalized_fulfills: monitor_pending_finalized_fulfills.unwrap(),
995210016
monitor_pending_update_adds: monitor_pending_update_adds.unwrap_or_default(),
10017+
monitor_pending_tx_signatures: None,
995310018

995410019
signer_pending_revoke_and_ack: false,
995510020
signer_pending_commitment_update: false,
@@ -10036,6 +10101,10 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, u32, &'c Ch
1003610101

1003710102
blocked_monitor_updates: blocked_monitor_updates.unwrap(),
1003810103
is_manual_broadcast: is_manual_broadcast.unwrap_or(false),
10104+
// If we've sent `commtiment_signed` for an interactively constructed transaction
10105+
// during a signing session, but have not received `tx_signatures` we MUST set `next_funding_txid`
10106+
// to the txid of that interactive transaction, else we MUST NOT set it.
10107+
next_funding_txid,
1003910108
},
1004010109
interactive_tx_signing_session: None,
1004110110
})

lightning/src/ln/channelmanager.rs

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3164,7 +3164,7 @@ macro_rules! handle_monitor_update_completion {
31643164
&mut $peer_state.pending_msg_events, $chan, updates.raa,
31653165
updates.commitment_update, updates.order, updates.accepted_htlcs, updates.pending_update_adds,
31663166
updates.funding_broadcastable, updates.channel_ready,
3167-
updates.announcement_sigs);
3167+
updates.announcement_sigs, updates.tx_signatures);
31683168
if let Some(upd) = channel_update {
31693169
$peer_state.pending_msg_events.push(upd);
31703170
}
@@ -7445,17 +7445,20 @@ where
74457445
commitment_update: Option<msgs::CommitmentUpdate>, order: RAACommitmentOrder,
74467446
pending_forwards: Vec<(PendingHTLCInfo, u64)>, pending_update_adds: Vec<msgs::UpdateAddHTLC>,
74477447
funding_broadcastable: Option<Transaction>,
7448-
channel_ready: Option<msgs::ChannelReady>, announcement_sigs: Option<msgs::AnnouncementSignatures>)
7449-
-> (Option<(u64, Option<PublicKey>, OutPoint, ChannelId, u128, Vec<(PendingHTLCInfo, u64)>)>, Option<(u64, Vec<msgs::UpdateAddHTLC>)>) {
7448+
channel_ready: Option<msgs::ChannelReady>, announcement_sigs: Option<msgs::AnnouncementSignatures>,
7449+
tx_signatures: Option<msgs::TxSignatures>
7450+
) -> (Option<(u64, Option<PublicKey>, OutPoint, ChannelId, u128, Vec<(PendingHTLCInfo, u64)>)>, Option<(u64, Vec<msgs::UpdateAddHTLC>)>) {
74507451
let logger = WithChannelContext::from(&self.logger, &channel.context, None);
7451-
log_trace!(logger, "Handling channel resumption for channel {} with {} RAA, {} commitment update, {} pending forwards, {} pending update_add_htlcs, {}broadcasting funding, {} channel ready, {} announcement",
7452+
log_trace!(logger, "Handling channel resumption for channel {} with {} RAA, {} commitment update, {} pending forwards, {} pending update_add_htlcs, {}broadcasting funding, {} channel ready, {} announcement, {} tx_signatures",
74527453
&channel.context.channel_id(),
74537454
if raa.is_some() { "an" } else { "no" },
74547455
if commitment_update.is_some() { "a" } else { "no" },
74557456
pending_forwards.len(), pending_update_adds.len(),
74567457
if funding_broadcastable.is_some() { "" } else { "not " },
74577458
if channel_ready.is_some() { "sending" } else { "without" },
7458-
if announcement_sigs.is_some() { "sending" } else { "without" });
7459+
if announcement_sigs.is_some() { "sending" } else { "without" },
7460+
if tx_signatures.is_some() { "sending" } else { "without" },
7461+
);
74597462

74607463
let counterparty_node_id = channel.context.get_counterparty_node_id();
74617464
let short_channel_id = channel.context.get_short_channel_id().unwrap_or(channel.context.outbound_scid_alias());
@@ -7482,6 +7485,12 @@ where
74827485
msg,
74837486
});
74847487
}
7488+
if let Some(msg) = tx_signatures {
7489+
pending_msg_events.push(events::MessageSendEvent::SendTxSignatures {
7490+
node_id: counterparty_node_id,
7491+
msg,
7492+
});
7493+
}
74857494

74867495
macro_rules! handle_cs { () => {
74877496
if let Some(update) = commitment_update {
@@ -8349,7 +8358,8 @@ where
83498358
let channel_phase = chan_phase_entry.get_mut();
83508359
match channel_phase {
83518360
ChannelPhase::Funded(chan) => {
8352-
let (tx_signatures_opt, funding_tx_opt) = try_chan_phase_entry!(self, peer_state, chan.tx_signatures(msg), chan_phase_entry);
8361+
let logger = WithChannelContext::from(&self.logger, &chan.context, None);
8362+
let (tx_signatures_opt, funding_tx_opt) = try_chan_phase_entry!(self, peer_state, chan.tx_signatures(msg, &&logger), chan_phase_entry);
83538363
if let Some(tx_signatures) = tx_signatures_opt {
83548364
peer_state.pending_msg_events.push(events::MessageSendEvent::SendTxSignatures {
83558365
node_id: *counterparty_node_id,
@@ -9222,7 +9232,7 @@ where
92229232
let need_lnd_workaround = chan.context.workaround_lnd_bug_4006.take();
92239233
let (htlc_forwards, decode_update_add_htlcs) = self.handle_channel_resumption(
92249234
&mut peer_state.pending_msg_events, chan, responses.raa, responses.commitment_update, responses.order,
9225-
Vec::new(), Vec::new(), None, responses.channel_ready, responses.announcement_sigs);
9235+
Vec::new(), Vec::new(), None, responses.channel_ready, responses.announcement_sigs, None);
92269236
debug_assert!(htlc_forwards.is_none());
92279237
debug_assert!(decode_update_add_htlcs.is_none());
92289238
if let Some(upd) = channel_update {

0 commit comments

Comments
 (0)