Skip to content

Commit 2cee42d

Browse files
committed
Handle re-establishment next_funding_txid
1 parent 8d2aa47 commit 2cee42d

File tree

3 files changed

+107
-29
lines changed

3 files changed

+107
-29
lines changed

lightning/src/ln/channel.rs

Lines changed: 89 additions & 21 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.txid());
1751+
};
1752+
1753+
HandleTxCompleteResult(Ok(tx_complete))
17211754
}
17221755

17231756
fn funding_tx_constructed<L: Deref>(
@@ -2071,6 +2104,7 @@ impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
20712104
monitor_pending_failures: Vec::new(),
20722105
monitor_pending_finalized_fulfills: Vec::new(),
20732106
monitor_pending_update_adds: Vec::new(),
2107+
monitor_pending_tx_signatures: None,
20742108

20752109
signer_pending_revoke_and_ack: false,
20762110
signer_pending_commitment_update: false,
@@ -2164,6 +2198,8 @@ impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
21642198
blocked_monitor_updates: Vec::new(),
21652199

21662200
is_manual_broadcast: false,
2201+
2202+
next_funding_txid: None,
21672203
};
21682204

21692205
Ok(channel_context)
@@ -2305,6 +2341,7 @@ impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
23052341
monitor_pending_failures: Vec::new(),
23062342
monitor_pending_finalized_fulfills: Vec::new(),
23072343
monitor_pending_update_adds: Vec::new(),
2344+
monitor_pending_tx_signatures: None,
23082345

23092346
signer_pending_revoke_and_ack: false,
23102347
signer_pending_commitment_update: false,
@@ -2395,6 +2432,7 @@ impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
23952432
blocked_monitor_updates: Vec::new(),
23962433
local_initiated_shutdown: None,
23972434
is_manual_broadcast: false,
2435+
next_funding_txid: None,
23982436
})
23992437
}
24002438

@@ -4949,6 +4987,14 @@ impl<SP: Deref> Channel<SP> where
49494987
self.context.channel_state = ChannelState::AwaitingChannelReady(AwaitingChannelReadyFlags::new());
49504988
self.monitor_updating_paused(false, false, need_channel_ready, Vec::new(), Vec::new(), Vec::new());
49514989

4990+
if let Some(tx_signatures) = self.interactive_tx_signing_session.as_mut().and_then(
4991+
|session| session.received_commitment_signed()
4992+
) {
4993+
// We're up first for submitting our tx_signatures, but our monitor has not persisted yet
4994+
// so they'll be sent as soon as that's done.
4995+
self.context.monitor_pending_tx_signatures = Some(tx_signatures);
4996+
}
4997+
49524998
Ok(channel_monitor)
49534999
}
49545000

@@ -5622,7 +5668,13 @@ impl<SP: Deref> Channel<SP> where
56225668
}
56235669
}
56245670

5625-
pub fn tx_signatures(&mut self, msg: &msgs::TxSignatures) -> Result<(Option<msgs::TxSignatures>, Option<Transaction>), ChannelError> {
5671+
pub fn tx_signatures<L: Deref>(&mut self, msg: &msgs::TxSignatures, logger: &L) -> Result<(Option<msgs::TxSignatures>, Option<Transaction>), ChannelError>
5672+
where L::Target: Logger
5673+
{
5674+
if !matches!(self.context.channel_state, ChannelState::FundingNegotiated) {
5675+
return Err(ChannelError::close("Received tx_signatures in strange state!".to_owned()));
5676+
}
5677+
56265678
if let Some(ref mut signing_session) = self.interactive_tx_signing_session {
56275679
if msg.witnesses.len() != signing_session.remote_inputs_count() {
56285680
return Err(ChannelError::Close(
@@ -5661,16 +5713,23 @@ impl<SP: Deref> Channel<SP> where
56615713
}
56625714
self.context.funding_transaction = funding_tx_opt.clone();
56635715

5716+
self.context.next_funding_txid = None;
5717+
56645718
// Clear out the signing session
56655719
self.interactive_tx_signing_session = None;
56665720

5721+
if tx_signatures_opt.is_some() && self.context.channel_state.is_monitor_update_in_progress() {
5722+
log_debug!(logger, "Not sending tx_signatures: a monitor update is in progress. Setting monitor_pending_tx_signatures.");
5723+
self.context.monitor_pending_tx_signatures = tx_signatures_opt;
5724+
return Ok((None, None));
5725+
}
5726+
56675727
Ok((tx_signatures_opt, funding_tx_opt))
56685728
} else {
5669-
return Err(ChannelError::Close(
5670-
(
5729+
Err(ChannelError::Close((
56715730
"Unexpected tx_signatures. No funding transaction awaiting signatures".to_string(),
56725731
ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(false) },
5673-
)));
5732+
)))
56745733
}
56755734
}
56765735

@@ -5907,14 +5966,18 @@ impl<SP: Deref> Channel<SP> where
59075966
mem::swap(&mut finalized_claimed_htlcs, &mut self.context.monitor_pending_finalized_fulfills);
59085967
let mut pending_update_adds = Vec::new();
59095968
mem::swap(&mut pending_update_adds, &mut self.context.monitor_pending_update_adds);
5969+
// For channels established with V2 establishment we won't send a `tx_signatures` when we're in
5970+
// MonitorUpdateInProgress (and we assume the user will never directly broadcast the funding
5971+
// transaction and waits for us to do it).
5972+
let tx_signatures = self.context.monitor_pending_tx_signatures.take();
59105973

59115974
if self.context.channel_state.is_peer_disconnected() {
59125975
self.context.monitor_pending_revoke_and_ack = false;
59135976
self.context.monitor_pending_commitment_signed = false;
59145977
return MonitorRestoreUpdates {
59155978
raa: None, commitment_update: None, order: RAACommitmentOrder::RevokeAndACKFirst,
59165979
accepted_htlcs, failed_htlcs, finalized_claimed_htlcs, pending_update_adds,
5917-
funding_broadcastable, channel_ready, announcement_sigs
5980+
funding_broadcastable, channel_ready, announcement_sigs, tx_signatures
59185981
};
59195982
}
59205983

@@ -5948,7 +6011,7 @@ impl<SP: Deref> Channel<SP> where
59486011
match order { RAACommitmentOrder::CommitmentFirst => "commitment", RAACommitmentOrder::RevokeAndACKFirst => "RAA"});
59496012
MonitorRestoreUpdates {
59506013
raa, commitment_update, order, accepted_htlcs, failed_htlcs, finalized_claimed_htlcs,
5951-
pending_update_adds, funding_broadcastable, channel_ready, announcement_sigs
6014+
pending_update_adds, funding_broadcastable, channel_ready, announcement_sigs, tx_signatures
59526015
}
59536016
}
59546017

@@ -7719,10 +7782,7 @@ impl<SP: Deref> Channel<SP> where
77197782
next_remote_commitment_number: INITIAL_COMMITMENT_NUMBER - self.context.cur_counterparty_commitment_transaction_number - 1,
77207783
your_last_per_commitment_secret: remote_last_secret,
77217784
my_current_per_commitment_point: dummy_pubkey,
7722-
// TODO(dual_funding): If we've sent `commtiment_signed` for an interactive transaction
7723-
// construction but have not received `tx_signatures` we MUST set `next_funding_txid` to the
7724-
// txid of that interactive transaction, else we MUST NOT set it.
7725-
next_funding_txid: None,
7785+
next_funding_txid: self.context.next_funding_txid,
77267786
}
77277787
}
77287788

@@ -9423,7 +9483,8 @@ impl<SP: Deref> Writeable for Channel<SP> where SP::Target: SignerProvider {
94239483
(47, next_holder_commitment_point, option),
94249484
(49, self.context.local_initiated_shutdown, option), // Added in 0.0.122
94259485
(51, is_manual_broadcast, option), // Added in 0.0.124
9426-
(53, funding_tx_broadcast_safe_event_emitted, option) // Added in 0.0.124
9486+
(53, funding_tx_broadcast_safe_event_emitted, option), // Added in 0.0.124
9487+
(55, self.context.next_funding_txid, option) // Added in 0.1.0
94279488
});
94289489

94299490
Ok(())
@@ -9713,6 +9774,7 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, u32, &'c Ch
97139774
let mut channel_pending_event_emitted = None;
97149775
let mut channel_ready_event_emitted = None;
97159776
let mut funding_tx_broadcast_safe_event_emitted = None;
9777+
let mut next_funding_txid = funding_transaction.as_ref().map(|tx| tx.compute_txid());
97169778

97179779
let mut user_id_high_opt: Option<u64> = None;
97189780
let mut channel_keys_id: Option<[u8; 32]> = None;
@@ -9773,6 +9835,7 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, u32, &'c Ch
97739835
(49, local_initiated_shutdown, option),
97749836
(51, is_manual_broadcast, option),
97759837
(53, funding_tx_broadcast_safe_event_emitted, option),
9838+
(55, next_funding_txid, option) // Added in 0.0.125
97769839
});
97779840

97789841
let (channel_keys_id, holder_signer) = if let Some(channel_keys_id) = channel_keys_id {
@@ -9946,6 +10009,7 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, u32, &'c Ch
994610009
monitor_pending_failures,
994710010
monitor_pending_finalized_fulfills: monitor_pending_finalized_fulfills.unwrap(),
994810011
monitor_pending_update_adds: monitor_pending_update_adds.unwrap_or_default(),
10012+
monitor_pending_tx_signatures: None,
994910013

995010014
signer_pending_revoke_and_ack: false,
995110015
signer_pending_commitment_update: false,
@@ -10032,6 +10096,10 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, u32, &'c Ch
1003210096

1003310097
blocked_monitor_updates: blocked_monitor_updates.unwrap(),
1003410098
is_manual_broadcast: is_manual_broadcast.unwrap_or(false),
10099+
// If we've sent `commtiment_signed` for an interactively constructed transaction
10100+
// during a signing session, but have not received `tx_signatures` we MUST set `next_funding_txid`
10101+
// to the txid of that interactive transaction, else we MUST NOT set it.
10102+
next_funding_txid,
1003510103
},
1003610104
interactive_tx_signing_session: None,
1003710105
})

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 {

lightning/src/ln/interactivetxs.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1379,7 +1379,7 @@ where
13791379
serial_id
13801380
}
13811381

1382-
enum HandleTxCompleteValue {
1382+
pub(super) enum HandleTxCompleteValue {
13831383
SendTxMessage(InteractiveTxMessageSend),
13841384
SendTxComplete(InteractiveTxMessageSend, InteractiveTxSigningSession),
13851385
NegotiationComplete(InteractiveTxSigningSession),

0 commit comments

Comments
 (0)