Skip to content

Commit 001bc71

Browse files
authored
Merge pull request #1121 from TheBlueMatt/2021-10-return-temp-id
Expose temporary channel ID and user channel ID pre-funding
2 parents 2398f17 + bb7ef6c commit 001bc71

File tree

5 files changed

+69
-35
lines changed

5 files changed

+69
-35
lines changed

fuzz/src/router.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,7 @@ pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
217217
funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
218218
short_channel_id: Some(scid),
219219
channel_value_satoshis: slice_to_be64(get_slice!(8)),
220-
user_id: 0, inbound_capacity_msat: 0,
220+
user_channel_id: 0, inbound_capacity_msat: 0,
221221
unspendable_punishment_reserve: None,
222222
confirmations_required: None,
223223
force_close_spend_delay: None,

lightning/src/ln/channelmanager.rs

+49-29
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,7 @@ type ShutdownResult = (Option<(OutPoint, ChannelMonitorUpdate)>, Vec<(HTLCSource
242242
243243
struct MsgHandleErrInternal {
244244
err: msgs::LightningError,
245-
chan_id: Option<[u8; 32]>, // If Some a channel of ours has been closed
245+
chan_id: Option<([u8; 32], u64)>, // If Some a channel of ours has been closed
246246
shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
247247
}
248248
impl MsgHandleErrInternal {
@@ -278,7 +278,7 @@ impl MsgHandleErrInternal {
278278
Self { err, chan_id: None, shutdown_finish: None }
279279
}
280280
#[inline]
281-
fn from_finish_shutdown(err: String, channel_id: [u8; 32], shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
281+
fn from_finish_shutdown(err: String, channel_id: [u8; 32], user_channel_id: u64, shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
282282
Self {
283283
err: LightningError {
284284
err: err.clone(),
@@ -289,7 +289,7 @@ impl MsgHandleErrInternal {
289289
},
290290
},
291291
},
292-
chan_id: Some(channel_id),
292+
chan_id: Some((channel_id, user_channel_id)),
293293
shutdown_finish: Some((shutdown_res, channel_update)),
294294
}
295295
}
@@ -776,8 +776,8 @@ pub struct ChannelDetails {
776776
///
777777
/// [`outbound_capacity_msat`]: ChannelDetails::outbound_capacity_msat
778778
pub unspendable_punishment_reserve: Option<u64>,
779-
/// The user_id passed in to create_channel, or 0 if the channel was inbound.
780-
pub user_id: u64,
779+
/// The `user_channel_id` passed in to create_channel, or 0 if the channel was inbound.
780+
pub user_channel_id: u64,
781781
/// The available outbound capacity for sending HTLCs to the remote peer. This does not include
782782
/// any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not
783783
/// available for inclusion in new outbound HTLCs). This further does not include any pending
@@ -894,8 +894,11 @@ macro_rules! handle_error {
894894
msg: update
895895
});
896896
}
897-
if let Some(channel_id) = chan_id {
898-
$self.pending_events.lock().unwrap().push(events::Event::ChannelClosed { channel_id, reason: ClosureReason::ProcessingError { err: err.err.clone() } });
897+
if let Some((channel_id, user_channel_id)) = chan_id {
898+
$self.pending_events.lock().unwrap().push(events::Event::ChannelClosed {
899+
channel_id, user_channel_id,
900+
reason: ClosureReason::ProcessingError { err: err.err.clone() }
901+
});
899902
}
900903
}
901904

@@ -937,15 +940,17 @@ macro_rules! convert_chan_err {
937940
$short_to_id.remove(&short_id);
938941
}
939942
let shutdown_res = $channel.force_shutdown(true);
940-
(true, MsgHandleErrInternal::from_finish_shutdown(msg, *$channel_id, shutdown_res, $self.get_channel_update_for_broadcast(&$channel).ok()))
943+
(true, MsgHandleErrInternal::from_finish_shutdown(msg, *$channel_id, $channel.get_user_id(),
944+
shutdown_res, $self.get_channel_update_for_broadcast(&$channel).ok()))
941945
},
942946
ChannelError::CloseDelayBroadcast(msg) => {
943947
log_error!($self.logger, "Channel {} need to be shutdown but closing transactions not broadcast due to {}", log_bytes!($channel_id[..]), msg);
944948
if let Some(short_id) = $channel.get_short_channel_id() {
945949
$short_to_id.remove(&short_id);
946950
}
947951
let shutdown_res = $channel.force_shutdown(false);
948-
(true, MsgHandleErrInternal::from_finish_shutdown(msg, *$channel_id, shutdown_res, $self.get_channel_update_for_broadcast(&$channel).ok()))
952+
(true, MsgHandleErrInternal::from_finish_shutdown(msg, *$channel_id, $channel.get_user_id(),
953+
shutdown_res, $self.get_channel_update_for_broadcast(&$channel).ok()))
949954
}
950955
}
951956
}
@@ -1013,7 +1018,7 @@ macro_rules! handle_monitor_err {
10131018
// splitting hairs we'd prefer to claim payments that were to us, but we haven't
10141019
// given up the preimage yet, so might as well just wait until the payment is
10151020
// retried, avoiding the on-chain fees.
1016-
let res: Result<(), _> = Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure".to_owned(), *$chan_id,
1021+
let res: Result<(), _> = Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure".to_owned(), *$chan_id, $chan.get_user_id(),
10171022
$chan.force_shutdown(true), $self.get_channel_update_for_broadcast(&$chan).ok() ));
10181023
(res, true)
10191024
},
@@ -1267,22 +1272,31 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
12671272

12681273
/// Creates a new outbound channel to the given remote node and with the given value.
12691274
///
1270-
/// user_id will be provided back as user_channel_id in FundingGenerationReady events to allow
1271-
/// tracking of which events correspond with which create_channel call. Note that the
1272-
/// user_channel_id defaults to 0 for inbound channels, so you may wish to avoid using 0 for
1273-
/// user_id here. user_id has no meaning inside of LDK, it is simply copied to events and
1274-
/// otherwise ignored.
1275-
///
1276-
/// If successful, will generate a SendOpenChannel message event, so you should probably poll
1277-
/// PeerManager::process_events afterwards.
1275+
/// `user_channel_id` will be provided back as in
1276+
/// [`Event::FundingGenerationReady::user_channel_id`] to allow tracking of which events
1277+
/// correspond with which `create_channel` call. Note that the `user_channel_id` defaults to 0
1278+
/// for inbound channels, so you may wish to avoid using 0 for `user_channel_id` here.
1279+
/// `user_channel_id` has no meaning inside of LDK, it is simply copied to events and otherwise
1280+
/// ignored.
12781281
///
1279-
/// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
1280-
/// greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
1282+
/// Raises [`APIError::APIMisuseError`] when `channel_value_satoshis` > 2**24 or `push_msat` is
1283+
/// greater than `channel_value_satoshis * 1k` or `channel_value_satoshis < 1000`.
12811284
///
12821285
/// Note that we do not check if you are currently connected to the given peer. If no
12831286
/// connection is available, the outbound `open_channel` message may fail to send, resulting in
1284-
/// the channel eventually being silently forgotten.
1285-
pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64, override_config: Option<UserConfig>) -> Result<(), APIError> {
1287+
/// the channel eventually being silently forgotten (dropped on reload).
1288+
///
1289+
/// Returns the new Channel's temporary `channel_id`. This ID will appear as
1290+
/// [`Event::FundingGenerationReady::temporary_channel_id`] and in
1291+
/// [`ChannelDetails::channel_id`] until after
1292+
/// [`ChannelManager::funding_transaction_generated`] is called, swapping the Channel's ID for
1293+
/// one derived from the funding transaction's TXID. If the counterparty rejects the channel
1294+
/// immediately, this temporary ID will appear in [`Event::ChannelClosed::channel_id`].
1295+
///
1296+
/// [`Event::FundingGenerationReady::user_channel_id`]: events::Event::FundingGenerationReady::user_channel_id
1297+
/// [`Event::FundingGenerationReady::temporary_channel_id`]: events::Event::FundingGenerationReady::temporary_channel_id
1298+
/// [`Event::ChannelClosed::channel_id`]: events::Event::ChannelClosed::channel_id
1299+
pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_channel_id: u64, override_config: Option<UserConfig>) -> Result<[u8; 32], APIError> {
12861300
if channel_value_satoshis < 1000 {
12871301
return Err(APIError::APIMisuseError { err: format!("Channel value must be at least 1000 satoshis. It was {}", channel_value_satoshis) });
12881302
}
@@ -1294,7 +1308,7 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
12941308
let peer_state = peer_state.lock().unwrap();
12951309
let their_features = &peer_state.latest_features;
12961310
let config = if override_config.is_some() { override_config.as_ref().unwrap() } else { &self.default_configuration };
1297-
Channel::new_outbound(&self.fee_estimator, &self.keys_manager, their_network_key, their_features, channel_value_satoshis, push_msat, user_id, config)?
1311+
Channel::new_outbound(&self.fee_estimator, &self.keys_manager, their_network_key, their_features, channel_value_satoshis, push_msat, user_channel_id, config)?
12981312
},
12991313
None => return Err(APIError::ChannelUnavailable { err: format!("Not connected to node: {}", their_network_key) }),
13001314
}
@@ -1305,8 +1319,9 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
13051319
// We want to make sure the lock is actually acquired by PersistenceNotifierGuard.
13061320
debug_assert!(&self.total_consistency_lock.try_write().is_err());
13071321

1322+
let temporary_channel_id = channel.channel_id();
13081323
let mut channel_state = self.channel_state.lock().unwrap();
1309-
match channel_state.by_id.entry(channel.channel_id()) {
1324+
match channel_state.by_id.entry(temporary_channel_id) {
13101325
hash_map::Entry::Occupied(_) => {
13111326
if cfg!(feature = "fuzztarget") {
13121327
return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG".to_owned() });
@@ -1320,7 +1335,7 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
13201335
node_id: their_network_key,
13211336
msg: res,
13221337
});
1323-
Ok(())
1338+
Ok(temporary_channel_id)
13241339
}
13251340

13261341
fn list_channels_with_filter<Fn: FnMut(&(&[u8; 32], &Channel<Signer>)) -> bool>(&self, f: Fn) -> Vec<ChannelDetails> {
@@ -1346,7 +1361,7 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
13461361
unspendable_punishment_reserve: to_self_reserve_satoshis,
13471362
inbound_capacity_msat,
13481363
outbound_capacity_msat,
1349-
user_id: channel.get_user_id(),
1364+
user_channel_id: channel.get_user_id(),
13501365
confirmations_required: channel.minimum_depth(),
13511366
force_close_spend_delay: channel.get_counterparty_selected_contest_delay(),
13521367
is_outbound: channel.is_outbound(),
@@ -1393,7 +1408,11 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
13931408
},
13941409
None => {},
13951410
}
1396-
pending_events_lock.push(events::Event::ChannelClosed { channel_id: channel.channel_id(), reason: closure_reason });
1411+
pending_events_lock.push(events::Event::ChannelClosed {
1412+
channel_id: channel.channel_id(),
1413+
user_channel_id: channel.get_user_id(),
1414+
reason: closure_reason
1415+
});
13971416
}
13981417

13991418
fn close_channel_internal(&self, channel_id: &[u8; 32], target_feerate_sats_per_1000_weight: Option<u32>) -> Result<(), APIError> {
@@ -2228,7 +2247,7 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
22282247

22292248
(chan.get_outbound_funding_created(funding_transaction, funding_txo, &self.logger)
22302249
.map_err(|e| if let ChannelError::Close(msg) = e {
2231-
MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.force_shutdown(true), None)
2250+
MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.get_user_id(), chan.force_shutdown(true), None)
22322251
} else { unreachable!(); })
22332252
, chan)
22342253
},
@@ -2570,7 +2589,7 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
25702589
channel_state.short_to_id.remove(&short_id);
25712590
}
25722591
// ChannelClosed event is generated by handle_error for us.
2573-
Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, channel.force_shutdown(true), self.get_channel_update_for_broadcast(&channel).ok()))
2592+
Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, channel.get_user_id(), channel.force_shutdown(true), self.get_channel_update_for_broadcast(&channel).ok()))
25742593
},
25752594
ChannelError::CloseDelayBroadcast(_) => { panic!("Wait is only generated on receipt of channel_reestablish, which is handled by try_chan_entry, we don't bother to support it here"); }
25762595
};
@@ -5609,6 +5628,7 @@ impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
56095628
monitor.broadcast_latest_holder_commitment_txn(&args.tx_broadcaster, &args.logger);
56105629
channel_closures.push(events::Event::ChannelClosed {
56115630
channel_id: channel.channel_id(),
5631+
user_channel_id: channel.get_user_id(),
56125632
reason: ClosureReason::OutdatedChannelManager
56135633
});
56145634
} else {

lightning/src/ln/functional_test_utils.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -527,11 +527,12 @@ pub fn create_funding_transaction<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, expected_
527527
}
528528

529529
pub fn create_chan_between_nodes_with_value_init<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, node_b: &Node<'a, 'b, 'c>, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> Transaction {
530-
node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
530+
let create_chan_id = node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
531531
node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), a_flags, &get_event_msg!(node_a, MessageSendEvent::SendOpenChannel, node_b.node.get_our_node_id()));
532532
node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), b_flags, &get_event_msg!(node_b, MessageSendEvent::SendAcceptChannel, node_a.node.get_our_node_id()));
533533

534534
let (temporary_channel_id, tx, funding_output) = create_funding_transaction(node_a, channel_value, 42);
535+
assert_eq!(temporary_channel_id, create_chan_id);
535536

536537
node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
537538
check_added_monitors!(node_a, 0);

lightning/src/routing/router.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1362,7 +1362,7 @@ mod tests {
13621362
funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
13631363
short_channel_id,
13641364
channel_value_satoshis: 0,
1365-
user_id: 0,
1365+
user_channel_id: 0,
13661366
outbound_capacity_msat,
13671367
inbound_capacity_msat: 42,
13681368
unspendable_punishment_reserve: None,

lightning/src/util/events.rs

+16-3
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,10 @@ pub enum Event {
146146
channel_value_satoshis: u64,
147147
/// The script which should be used in the transaction output.
148148
output_script: Script,
149-
/// The value passed in to ChannelManager::create_channel
149+
/// The `user_channel_id` value passed in to [`ChannelManager::create_channel`], or 0 for
150+
/// an inbound channel.
151+
///
152+
/// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
150153
user_channel_id: u64,
151154
},
152155
/// Indicates we've received money! Just gotta dig out that payment preimage and feed it to
@@ -262,6 +265,12 @@ pub enum Event {
262265
/// The channel_id of the channel which has been closed. Note that on-chain transactions
263266
/// resolving the channel are likely still awaiting confirmation.
264267
channel_id: [u8; 32],
268+
/// The `user_channel_id` value passed in to [`ChannelManager::create_channel`], or 0 for
269+
/// an inbound channel. This will always be zero for objects serialized with LDK versions
270+
/// prior to 0.0.102.
271+
///
272+
/// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
273+
user_channel_id: u64,
265274
/// The reason the channel was closed.
266275
reason: ClosureReason
267276
},
@@ -352,10 +361,11 @@ impl Writeable for Event {
352361
(2, claim_from_onchain_tx, required),
353362
});
354363
},
355-
&Event::ChannelClosed { ref channel_id, ref reason } => {
364+
&Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason } => {
356365
9u8.write(writer)?;
357366
write_tlv_fields!(writer, {
358367
(0, channel_id, required),
368+
(1, user_channel_id, required),
359369
(2, reason, required)
360370
});
361371
},
@@ -492,12 +502,15 @@ impl MaybeReadable for Event {
492502
let f = || {
493503
let mut channel_id = [0; 32];
494504
let mut reason = None;
505+
let mut user_channel_id_opt = None;
495506
read_tlv_fields!(reader, {
496507
(0, channel_id, required),
508+
(1, user_channel_id_opt, option),
497509
(2, reason, ignorable),
498510
});
499511
if reason.is_none() { return Ok(None); }
500-
Ok(Some(Event::ChannelClosed { channel_id, reason: reason.unwrap() }))
512+
let user_channel_id = if let Some(id) = user_channel_id_opt { id } else { 0 };
513+
Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: reason.unwrap() }))
501514
};
502515
f()
503516
},

0 commit comments

Comments
 (0)