Skip to content

Commit 1b4d8e4

Browse files
authored
Merge pull request #4185 from TheBlueMatt/2025-10-0.2-backports
0.2 backports
2 parents 244fcf3 + 206fb06 commit 1b4d8e4

32 files changed

+2442
-546
lines changed

fuzz/src/full_stack.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ struct Peer<'a> {
195195
peers_connected: &'a RefCell<[bool; 256]>,
196196
}
197197
impl<'a> SocketDescriptor for Peer<'a> {
198-
fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
198+
fn send_data(&mut self, data: &[u8], _continue_read: bool) -> usize {
199199
data.len()
200200
}
201201
fn disconnect_socket(&mut self) {
@@ -695,7 +695,7 @@ pub fn do_test(mut data: &[u8], logger: &Arc<dyn Logger>) {
695695
}
696696
let mut peer = Peer { id: peer_id, peers_connected: &peers };
697697
match loss_detector.handler.read_event(&mut peer, get_slice!(get_slice!(1)[0])) {
698-
Ok(res) => assert!(!res),
698+
Ok(()) => {},
699699
Err(_) => {
700700
peers.borrow_mut()[peer_id as usize] = false;
701701
},

lightning-background-processor/src/lib.rs

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -300,7 +300,7 @@ where
300300

301301
/// Updates scorer based on event and returns whether an update occurred so we can decide whether
302302
/// to persist.
303-
fn update_scorer<'a, S: Deref<Target = SC> + Send + Sync, SC: 'a + WriteableScore<'a>>(
303+
fn update_scorer<'a, S: Deref<Target = SC>, SC: 'a + WriteableScore<'a>>(
304304
scorer: &'a S, event: &Event, duration_since_epoch: Duration,
305305
) -> bool {
306306
match event {
@@ -774,7 +774,7 @@ use futures_util::{dummy_waker, Joiner, OptionalSelector, Selector, SelectorOutp
774774
/// # #[derive(Eq, PartialEq, Clone, Hash)]
775775
/// # struct SocketDescriptor {}
776776
/// # impl lightning::ln::peer_handler::SocketDescriptor for SocketDescriptor {
777-
/// # fn send_data(&mut self, _data: &[u8], _resume_read: bool) -> usize { 0 }
777+
/// # fn send_data(&mut self, _data: &[u8], _continue_read: bool) -> usize { 0 }
778778
/// # fn disconnect_socket(&mut self) {}
779779
/// # }
780780
/// # type ChainMonitor<B, F, FE> = lightning::chain::chainmonitor::ChainMonitor<lightning::sign::InMemorySigner, Arc<F>, Arc<B>, Arc<FE>, Arc<Logger>, Arc<StoreSync>, Arc<lightning::sign::KeysManager>>;
@@ -887,10 +887,8 @@ pub async fn process_events_async<
887887
P: Deref,
888888
EventHandlerFuture: core::future::Future<Output = Result<(), ReplayEvent>>,
889889
EventHandler: Fn(Event) -> EventHandlerFuture,
890-
ES: Deref + Send,
891-
M: Deref<Target = ChainMonitor<<CM::Target as AChannelManager>::Signer, CF, T, F, L, P, ES>>
892-
+ Send
893-
+ Sync,
890+
ES: Deref,
891+
M: Deref<Target = ChainMonitor<<CM::Target as AChannelManager>::Signer, CF, T, F, L, P, ES>>,
894892
CM: Deref,
895893
OM: Deref,
896894
PGS: Deref<Target = P2PGossipSync<G, UL, L>>,
@@ -901,7 +899,7 @@ pub async fn process_events_async<
901899
O: Deref,
902900
K: Deref,
903901
OS: Deref<Target = OutputSweeper<T, D, F, CF, K, L, O>>,
904-
S: Deref<Target = SC> + Send + Sync,
902+
S: Deref<Target = SC>,
905903
SC: for<'b> WriteableScore<'b>,
906904
SleepFuture: core::future::Future<Output = bool> + core::marker::Unpin,
907905
Sleeper: Fn(Duration) -> SleepFuture,
@@ -1356,15 +1354,13 @@ pub async fn process_events_async_with_kv_store_sync<
13561354
T: Deref,
13571355
F: Deref,
13581356
G: Deref<Target = NetworkGraph<L>>,
1359-
L: Deref + Send + Sync,
1357+
L: Deref,
13601358
P: Deref,
13611359
EventHandlerFuture: core::future::Future<Output = Result<(), ReplayEvent>>,
13621360
EventHandler: Fn(Event) -> EventHandlerFuture,
1363-
ES: Deref + Send,
1364-
M: Deref<Target = ChainMonitor<<CM::Target as AChannelManager>::Signer, CF, T, F, L, P, ES>>
1365-
+ Send
1366-
+ Sync,
1367-
CM: Deref + Send + Sync,
1361+
ES: Deref,
1362+
M: Deref<Target = ChainMonitor<<CM::Target as AChannelManager>::Signer, CF, T, F, L, P, ES>>,
1363+
CM: Deref,
13681364
OM: Deref,
13691365
PGS: Deref<Target = P2PGossipSync<G, UL, L>>,
13701366
RGS: Deref<Target = RapidGossipSync<G, L>>,
@@ -1374,7 +1370,7 @@ pub async fn process_events_async_with_kv_store_sync<
13741370
O: Deref,
13751371
K: Deref,
13761372
OS: Deref<Target = OutputSweeperSync<T, D, F, CF, K, L, O>>,
1377-
S: Deref<Target = SC> + Send + Sync,
1373+
S: Deref<Target = SC>,
13781374
SC: for<'b> WriteableScore<'b>,
13791375
SleepFuture: core::future::Future<Output = bool> + core::marker::Unpin,
13801376
Sleeper: Fn(Duration) -> SleepFuture,
@@ -1878,7 +1874,7 @@ mod tests {
18781874
#[derive(Clone, Hash, PartialEq, Eq)]
18791875
struct TestDescriptor {}
18801876
impl SocketDescriptor for TestDescriptor {
1881-
fn send_data(&mut self, _data: &[u8], _resume_read: bool) -> usize {
1877+
fn send_data(&mut self, _data: &[u8], _continue_read: bool) -> usize {
18821878
0
18831879
}
18841880

lightning-net-tokio/src/lib.rs

Lines changed: 8 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -243,13 +243,8 @@ impl Connection {
243243
Ok(len) => {
244244
let read_res =
245245
peer_manager.as_ref().read_event(&mut our_descriptor, &buf[0..len]);
246-
let mut us_lock = us.lock().unwrap();
247246
match read_res {
248-
Ok(pause_read) => {
249-
if pause_read {
250-
us_lock.read_paused = true;
251-
}
252-
},
247+
Ok(()) => {},
253248
Err(_) => break Disconnect::CloseConnection,
254249
}
255250
},
@@ -533,7 +528,7 @@ impl SocketDescriptor {
533528
}
534529
}
535530
impl peer_handler::SocketDescriptor for SocketDescriptor {
536-
fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize {
531+
fn send_data(&mut self, data: &[u8], continue_read: bool) -> usize {
537532
// To send data, we take a lock on our Connection to access the TcpStream, writing to it if
538533
// there's room in the kernel buffer, or otherwise create a new Waker with a
539534
// SocketDescriptor in it which can wake up the write_avail Sender, waking up the
@@ -544,13 +539,16 @@ impl peer_handler::SocketDescriptor for SocketDescriptor {
544539
return 0;
545540
}
546541

547-
if resume_read && us.read_paused {
542+
let read_was_paused = us.read_paused;
543+
us.read_paused = !continue_read;
544+
545+
if continue_read && read_was_paused {
548546
// The schedule_read future may go to lock up but end up getting woken up by there
549547
// being more room in the write buffer, dropping the other end of this Sender
550548
// before we get here, so we ignore any failures to wake it up.
551-
us.read_paused = false;
552549
let _ = us.read_waker.try_send(());
553550
}
551+
554552
if data.is_empty() {
555553
return 0;
556554
}
@@ -576,16 +574,7 @@ impl peer_handler::SocketDescriptor for SocketDescriptor {
576574
}
577575
},
578576
task::Poll::Ready(Err(_)) => return written_len,
579-
task::Poll::Pending => {
580-
// We're queued up for a write event now, but we need to make sure we also
581-
// pause read given we're now waiting on the remote end to ACK (and in
582-
// accordance with the send_data() docs).
583-
us.read_paused = true;
584-
// Further, to avoid any current pending read causing a `read_event` call, wake
585-
// up the read_waker and restart its loop.
586-
let _ = us.read_waker.try_send(());
587-
return written_len;
588-
},
577+
task::Poll::Pending => return written_len,
589578
}
590579
}
591580
}

lightning-tests/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ lightning-types = { path = "../lightning-types", features = ["_test_utils"] }
1414
lightning-invoice = { path = "../lightning-invoice", default-features = false }
1515
lightning-macros = { path = "../lightning-macros" }
1616
lightning = { path = "../lightning", features = ["_test_utils"] }
17-
lightning_0_1 = { package = "lightning", version = "0.1.1", features = ["_test_utils"] }
17+
lightning_0_1 = { package = "lightning", version = "0.1.7", features = ["_test_utils"] }
1818
lightning_0_0_125 = { package = "lightning", version = "0.0.125", features = ["_test_utils"] }
1919

2020
bitcoin = { version = "0.32.2", default-features = false }

lightning-tests/src/upgrade_downgrade_tests.rs

Lines changed: 202 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,15 @@
1010
//! Tests which test upgrading from previous versions of LDK or downgrading to previous versions of
1111
//! LDK.
1212
13+
use lightning_0_1::commitment_signed_dance as commitment_signed_dance_0_1;
1314
use lightning_0_1::events::ClosureReason as ClosureReason_0_1;
15+
use lightning_0_1::expect_pending_htlcs_forwardable_ignore as expect_pending_htlcs_forwardable_ignore_0_1;
1416
use lightning_0_1::get_monitor as get_monitor_0_1;
17+
use lightning_0_1::ln::channelmanager::PaymentId as PaymentId_0_1;
18+
use lightning_0_1::ln::channelmanager::RecipientOnionFields as RecipientOnionFields_0_1;
1519
use lightning_0_1::ln::functional_test_utils as lightning_0_1_utils;
20+
use lightning_0_1::ln::msgs::ChannelMessageHandler as _;
21+
use lightning_0_1::routing::router as router_0_1;
1622
use lightning_0_1::util::ser::Writeable as _;
1723

1824
use lightning_0_0_125::chain::ChannelMonitorUpdateStatus as ChannelMonitorUpdateStatus_0_0_125;
@@ -29,16 +35,23 @@ use lightning_0_0_125::ln::msgs::ChannelMessageHandler as _;
2935
use lightning_0_0_125::routing::router as router_0_0_125;
3036
use lightning_0_0_125::util::ser::Writeable as _;
3137

32-
use lightning::chain::channelmonitor::ANTI_REORG_DELAY;
33-
use lightning::events::{ClosureReason, Event};
38+
use lightning::chain::channelmonitor::{ANTI_REORG_DELAY, HTLC_FAIL_BACK_BUFFER};
39+
use lightning::events::bump_transaction::sync::WalletSourceSync;
40+
use lightning::events::{ClosureReason, Event, HTLCHandlingFailureType};
3441
use lightning::ln::functional_test_utils::*;
42+
use lightning::ln::funding::SpliceContribution;
43+
use lightning::ln::msgs::BaseMessageHandler as _;
44+
use lightning::ln::msgs::ChannelMessageHandler as _;
45+
use lightning::ln::msgs::MessageSendEvent;
46+
use lightning::ln::splicing_tests::*;
47+
use lightning::ln::types::ChannelId;
3548
use lightning::sign::OutputSpender;
3649

37-
use lightning_types::payment::PaymentPreimage;
50+
use lightning_types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
3851

39-
use bitcoin::opcodes;
4052
use bitcoin::script::Builder;
4153
use bitcoin::secp256k1::Secp256k1;
54+
use bitcoin::{opcodes, Amount, TxOut};
4255

4356
use std::sync::Arc;
4457

@@ -299,3 +312,188 @@ fn test_0_1_legacy_remote_key_derivation() {
299312
panic!("Wrong event");
300313
}
301314
}
315+
316+
fn do_test_0_1_htlc_forward_after_splice(fail_htlc: bool) {
317+
// Test what happens if an HTLC set to be forwarded in 0.1 is forwarded after the inbound
318+
// channel is spliced. In the initial splice code, this could have led to a dangling HTLC if
319+
// the HTLC is failed as the backwards-failure would use the channel's original SCID which is
320+
// no longer valid.
321+
// In some later splice code, this also failed because the `KeysManager` would have tried to
322+
// rotate the `to_remote` key, which we aren't able to do in the splicing protocol.
323+
let (node_a_ser, node_b_ser, node_c_ser, mon_a_1_ser, mon_b_1_ser, mon_b_2_ser, mon_c_1_ser);
324+
let (node_a_id, node_b_id, node_c_id);
325+
let (chan_id_bytes_a, chan_id_bytes_b);
326+
let (payment_secret_bytes, payment_hash_bytes, payment_preimage_bytes);
327+
let (node_a_blocks, node_b_blocks, node_c_blocks);
328+
329+
const EXTRA_BLOCKS_BEFORE_FAIL: u32 = 145;
330+
331+
{
332+
let chanmon_cfgs = lightning_0_1_utils::create_chanmon_cfgs(3);
333+
let node_cfgs = lightning_0_1_utils::create_node_cfgs(3, &chanmon_cfgs);
334+
let node_chanmgrs =
335+
lightning_0_1_utils::create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
336+
let nodes = lightning_0_1_utils::create_network(3, &node_cfgs, &node_chanmgrs);
337+
338+
node_a_id = nodes[0].node.get_our_node_id();
339+
node_b_id = nodes[1].node.get_our_node_id();
340+
node_c_id = nodes[2].node.get_our_node_id();
341+
let chan_id_a = lightning_0_1_utils::create_announced_chan_between_nodes_with_value(
342+
&nodes, 0, 1, 10_000_000, 0,
343+
)
344+
.2;
345+
chan_id_bytes_a = chan_id_a.0;
346+
347+
let chan_id_b = lightning_0_1_utils::create_announced_chan_between_nodes_with_value(
348+
&nodes, 1, 2, 50_000, 0,
349+
)
350+
.2;
351+
chan_id_bytes_b = chan_id_b.0;
352+
353+
// Ensure all nodes are at the same initial height.
354+
let node_max_height = nodes.iter().map(|node| node.best_block_info().1).max().unwrap();
355+
for node in &nodes {
356+
let blocks_to_mine = node_max_height - node.best_block_info().1;
357+
if blocks_to_mine > 0 {
358+
lightning_0_1_utils::connect_blocks(node, blocks_to_mine);
359+
}
360+
}
361+
362+
let (preimage, hash, secret) =
363+
lightning_0_1_utils::get_payment_preimage_hash(&nodes[2], Some(1_000_000), None);
364+
payment_preimage_bytes = preimage.0;
365+
payment_hash_bytes = hash.0;
366+
payment_secret_bytes = secret.0;
367+
368+
let pay_params = router_0_1::PaymentParameters::from_node_id(
369+
node_c_id,
370+
lightning_0_1_utils::TEST_FINAL_CLTV,
371+
)
372+
.with_bolt11_features(nodes[2].node.bolt11_invoice_features())
373+
.unwrap();
374+
375+
let route_params =
376+
router_0_1::RouteParameters::from_payment_params_and_value(pay_params, 1_000_000);
377+
let mut route = lightning_0_1_utils::get_route(&nodes[0], &route_params).unwrap();
378+
route.paths[0].hops[1].cltv_expiry_delta =
379+
EXTRA_BLOCKS_BEFORE_FAIL + HTLC_FAIL_BACK_BUFFER + 1;
380+
if fail_htlc {
381+
// Pay more than the channel's value (and probably not enough fee)
382+
route.paths[0].hops[1].fee_msat = 50_000_000;
383+
}
384+
385+
let onion = RecipientOnionFields_0_1::secret_only(secret);
386+
let id = PaymentId_0_1(hash.0);
387+
nodes[0].node.send_payment_with_route(route, hash, onion, id).unwrap();
388+
389+
lightning_0_1_utils::check_added_monitors(&nodes[0], 1);
390+
let send_event = lightning_0_1_utils::SendEvent::from_node(&nodes[0]);
391+
392+
nodes[1].node.handle_update_add_htlc(node_a_id, &send_event.msgs[0]);
393+
commitment_signed_dance_0_1!(nodes[1], nodes[0], send_event.commitment_msg, false);
394+
expect_pending_htlcs_forwardable_ignore_0_1!(nodes[1]);
395+
396+
// We now have an HTLC pending in node B's forwarding queue with the original channel's
397+
// SCID as the source.
398+
// We now upgrade to 0.2 and splice before forwarding that HTLC...
399+
node_a_ser = nodes[0].node.encode();
400+
node_b_ser = nodes[1].node.encode();
401+
node_c_ser = nodes[2].node.encode();
402+
mon_a_1_ser = get_monitor_0_1!(nodes[0], chan_id_a).encode();
403+
mon_b_1_ser = get_monitor_0_1!(nodes[1], chan_id_a).encode();
404+
mon_b_2_ser = get_monitor_0_1!(nodes[1], chan_id_b).encode();
405+
mon_c_1_ser = get_monitor_0_1!(nodes[2], chan_id_b).encode();
406+
407+
node_a_blocks = Arc::clone(&nodes[0].blocks);
408+
node_b_blocks = Arc::clone(&nodes[1].blocks);
409+
node_c_blocks = Arc::clone(&nodes[2].blocks);
410+
}
411+
412+
// Create a dummy node to reload over with the 0.1 state
413+
let mut chanmon_cfgs = create_chanmon_cfgs(3);
414+
415+
// Our TestChannelSigner will fail as we're jumping ahead, so disable its state-based checks
416+
chanmon_cfgs[0].keys_manager.disable_all_state_policy_checks = true;
417+
chanmon_cfgs[1].keys_manager.disable_all_state_policy_checks = true;
418+
chanmon_cfgs[2].keys_manager.disable_all_state_policy_checks = true;
419+
420+
chanmon_cfgs[0].tx_broadcaster.blocks = node_a_blocks;
421+
chanmon_cfgs[1].tx_broadcaster.blocks = node_b_blocks;
422+
chanmon_cfgs[2].tx_broadcaster.blocks = node_c_blocks;
423+
424+
let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
425+
let (persister_a, persister_b, persister_c, chain_mon_a, chain_mon_b, chain_mon_c);
426+
let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
427+
let (node_a, node_b, node_c);
428+
let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
429+
430+
let config = test_default_channel_config();
431+
let a_mons = &[&mon_a_1_ser[..]];
432+
reload_node!(nodes[0], config.clone(), &node_a_ser, a_mons, persister_a, chain_mon_a, node_a);
433+
let b_mons = &[&mon_b_1_ser[..], &mon_b_2_ser[..]];
434+
reload_node!(nodes[1], config.clone(), &node_b_ser, b_mons, persister_b, chain_mon_b, node_b);
435+
let c_mons = &[&mon_c_1_ser[..]];
436+
reload_node!(nodes[2], config, &node_c_ser, c_mons, persister_c, chain_mon_c, node_c);
437+
438+
reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
439+
let mut reconnect_b_c_args = ReconnectArgs::new(&nodes[1], &nodes[2]);
440+
reconnect_b_c_args.send_channel_ready = (true, true);
441+
reconnect_b_c_args.send_announcement_sigs = (true, true);
442+
reconnect_nodes(reconnect_b_c_args);
443+
444+
let contribution = SpliceContribution::SpliceOut {
445+
outputs: vec![TxOut {
446+
value: Amount::from_sat(1_000),
447+
script_pubkey: nodes[0].wallet_source.get_change_script().unwrap(),
448+
}],
449+
};
450+
let splice_tx = splice_channel(&nodes[0], &nodes[1], ChannelId(chan_id_bytes_a), contribution);
451+
for node in nodes.iter() {
452+
mine_transaction(node, &splice_tx);
453+
connect_blocks(node, ANTI_REORG_DELAY - 1);
454+
}
455+
456+
let splice_locked = get_event_msg!(nodes[0], MessageSendEvent::SendSpliceLocked, node_b_id);
457+
lock_splice(&nodes[0], &nodes[1], &splice_locked, false);
458+
459+
for node in nodes.iter() {
460+
connect_blocks(node, EXTRA_BLOCKS_BEFORE_FAIL - ANTI_REORG_DELAY);
461+
}
462+
463+
// Now release the HTLC to be failed back to node A
464+
nodes[1].node.process_pending_htlc_forwards();
465+
466+
let pay_secret = PaymentSecret(payment_secret_bytes);
467+
let pay_hash = PaymentHash(payment_hash_bytes);
468+
let pay_preimage = PaymentPreimage(payment_preimage_bytes);
469+
470+
if fail_htlc {
471+
let failure = HTLCHandlingFailureType::Forward {
472+
node_id: Some(node_c_id),
473+
channel_id: ChannelId(chan_id_bytes_b),
474+
};
475+
expect_and_process_pending_htlcs_and_htlc_handling_failed(&nodes[1], &[failure]);
476+
check_added_monitors(&nodes[1], 1);
477+
478+
let updates = get_htlc_update_msgs(&nodes[1], &node_a_id);
479+
nodes[0].node.handle_update_fail_htlc(node_b_id, &updates.update_fail_htlcs[0]);
480+
commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
481+
let conditions = PaymentFailedConditions::new();
482+
expect_payment_failed_conditions(&nodes[0], pay_hash, false, conditions);
483+
} else {
484+
check_added_monitors(&nodes[1], 1);
485+
let forward_event = SendEvent::from_node(&nodes[1]);
486+
nodes[2].node.handle_update_add_htlc(node_b_id, &forward_event.msgs[0]);
487+
commitment_signed_dance!(nodes[2], nodes[1], forward_event.commitment_msg, false);
488+
489+
expect_and_process_pending_htlcs(&nodes[2], false);
490+
expect_payment_claimable!(nodes[2], pay_hash, pay_secret, 1_000_000);
491+
claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], pay_preimage);
492+
}
493+
}
494+
495+
#[test]
496+
fn test_0_1_htlc_forward_after_splice() {
497+
do_test_0_1_htlc_forward_after_splice(true);
498+
do_test_0_1_htlc_forward_after_splice(false);
499+
}

0 commit comments

Comments
 (0)