Skip to content

Commit 6d9a167

Browse files
Add reorg property test and refactor funding logic
Introduced a property test to verify reorg handling during both channel opening and closing (normal and force close). Added `invalidate_block` helper to roll back the chain and regenerate blocks to the previous height. Split `premine_and_distribute_funds` into `premine_blocks` and `distribute_funds` for better reusability, allowing the reorg test to pre-mine once and only distribute funds in each test round, improving efficiency.
1 parent 3d35691 commit 6d9a167

File tree

2 files changed

+264
-6
lines changed

2 files changed

+264
-6
lines changed

tests/common/mod.rs

Lines changed: 45 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,9 @@ use electrum_client::ElectrumApi;
4040

4141
use rand::distributions::Alphanumeric;
4242
use rand::{thread_rng, Rng};
43+
use serde_json::{json, Value};
4344

45+
use std::collections::HashMap;
4446
use std::env;
4547
use std::path::PathBuf;
4648
use std::sync::{Arc, RwLock};
@@ -395,6 +397,21 @@ pub(crate) fn generate_blocks_and_wait<E: ElectrumApi>(
395397
println!("\n");
396398
}
397399

400+
pub(crate) fn invalidate_blocks(bitcoind: &BitcoindClient, num_blocks: usize) {
401+
let blockchain_info = bitcoind.get_blockchain_info().expect("failed to get blockchain info");
402+
let cur_height = blockchain_info.blocks as usize;
403+
let target_height = cur_height - num_blocks + 1;
404+
let block_hash = bitcoind
405+
.get_block_hash(target_height as u64)
406+
.expect("failed to get block hash")
407+
.block_hash()
408+
.expect("block hash should be present");
409+
bitcoind.invalidate_block(block_hash).expect("failed to invalidate block");
410+
let blockchain_info = bitcoind.get_blockchain_info().expect("failed to get blockchain info");
411+
let new_cur_height = blockchain_info.blocks as usize;
412+
assert!(new_cur_height + num_blocks == cur_height);
413+
}
414+
398415
pub(crate) fn wait_for_block<E: ElectrumApi>(electrs: &E, min_height: usize) {
399416
let mut header = match electrs.block_headers_subscribe() {
400417
Ok(header) => header,
@@ -470,22 +487,42 @@ where
470487
pub(crate) fn premine_and_distribute_funds<E: ElectrumApi>(
471488
bitcoind: &BitcoindClient, electrs: &E, addrs: Vec<Address>, amount: Amount,
472489
) {
490+
premine_blocks(bitcoind, electrs);
491+
492+
distribute_funds(bitcoind, electrs, addrs, amount);
493+
}
494+
495+
pub(crate) fn premine_blocks<E: ElectrumApi>(bitcoind: &BitcoindClient, electrs: &E) {
473496
let _ = bitcoind.create_wallet("ldk_node_test");
474497
let _ = bitcoind.load_wallet("ldk_node_test");
475498
generate_blocks_and_wait(bitcoind, electrs, 101);
499+
}
500+
pub(crate) fn distribute_funds<E: ElectrumApi>(
501+
bitcoind: &BitcoindClient, electrs: &E, addrs: Vec<Address>, amount: Amount,
502+
) -> Txid {
503+
let amounts: HashMap<String, f64> =
504+
addrs.iter().map(|addr| (addr.to_string(), amount.to_btc())).collect();
505+
506+
let empty_account = json!("");
507+
let amounts_json = json!(amounts);
508+
let txid = bitcoind
509+
.call::<Value>("sendmany", &[empty_account, amounts_json])
510+
.unwrap()
511+
.as_str()
512+
.unwrap()
513+
.parse()
514+
.unwrap();
476515

477-
for addr in addrs {
478-
let txid = bitcoind.send_to_address(&addr, amount).unwrap().0.parse().unwrap();
479-
wait_for_tx(electrs, txid);
480-
}
481-
516+
wait_for_tx(electrs, txid);
482517
generate_blocks_and_wait(bitcoind, electrs, 1);
518+
519+
txid
483520
}
484521

485522
pub fn open_channel(
486523
node_a: &TestNode, node_b: &TestNode, funding_amount_sat: u64, should_announce: bool,
487524
electrsd: &ElectrsD,
488-
) {
525+
) -> OutPoint {
489526
if should_announce {
490527
node_a
491528
.open_announced_channel(
@@ -513,6 +550,8 @@ pub fn open_channel(
513550
let funding_txo_b = expect_channel_pending_event!(node_b, node_a.node_id());
514551
assert_eq!(funding_txo_a, funding_txo_b);
515552
wait_for_tx(&electrsd.client, funding_txo_a.txid);
553+
554+
funding_txo_a
516555
}
517556

518557
pub(crate) fn do_channel_full_cycle<E: ElectrumApi>(

tests/reorg_test.rs

Lines changed: 219 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,219 @@
1+
mod common;
2+
use bitcoin::Amount;
3+
use electrsd::corepc_node::Node as BitcoinD;
4+
use electrsd::ElectrsD;
5+
use ldk_node::payment::{PaymentDirection, PaymentKind};
6+
use ldk_node::{Event, LightningBalance, PendingSweepBalance};
7+
use proptest::prelude::*;
8+
use std::collections::HashMap;
9+
use std::sync::OnceLock;
10+
11+
use crate::common::open_channel;
12+
use crate::common::setup_bitcoind_and_electrsd;
13+
use crate::common::{
14+
distribute_funds, expect_event, generate_blocks_and_wait, invalidate_blocks, premine_blocks,
15+
random_config, setup_node, wait_for_outpoint_spend, TestChainSource,
16+
};
17+
18+
static SETUP_REORG: OnceLock<(BitcoinD, ElectrsD)> = OnceLock::new();
19+
20+
fn init_setup_test_reorg() -> &'static (BitcoinD, ElectrsD) {
21+
SETUP_REORG.get_or_init(|| {
22+
let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
23+
let (bitcoind_client, electrsd_client) = (&bitcoind.client, &electrsd.client);
24+
premine_blocks(bitcoind_client, electrsd_client);
25+
(bitcoind, electrsd)
26+
})
27+
}
28+
29+
proptest! {
30+
#![proptest_config(ProptestConfig::with_cases(5))]
31+
#[test]
32+
fn reorg_test(
33+
reorg_depth in 1..=6usize,
34+
force_close in prop::bool::ANY,
35+
) {
36+
37+
let (bitcoind, electrsd) = init_setup_test_reorg();
38+
let chain_source_bitcoind = TestChainSource::BitcoindRpcSync(&bitcoind);
39+
let chain_source_electrsd = TestChainSource::Electrum(&electrsd);
40+
let chain_source_esplora = TestChainSource::Esplora(&electrsd);
41+
42+
macro_rules! config_node {
43+
($chain_source: expr, $anchor_channels: expr) => {{
44+
let config_a = random_config($anchor_channels);
45+
let node = setup_node(&$chain_source, config_a, None);
46+
node
47+
}};
48+
}
49+
let anchor_channels = true;
50+
let nodes = vec![
51+
config_node!(chain_source_electrsd, anchor_channels),
52+
config_node!(chain_source_bitcoind, anchor_channels),
53+
config_node!(chain_source_esplora, anchor_channels),
54+
];
55+
56+
let (bitcoind, electrs) = (&bitcoind.client, &electrsd.client);
57+
macro_rules! reorg {
58+
($reorg_depth: expr) => {{
59+
invalidate_blocks(bitcoind, $reorg_depth);
60+
generate_blocks_and_wait(bitcoind, electrs, $reorg_depth);
61+
}};
62+
}
63+
64+
let amount = 2_100_000;
65+
let addr_nodes =
66+
nodes.iter().map(|node| node.onchain_payment().new_address().unwrap()).collect::<Vec<_>>();
67+
distribute_funds(bitcoind, electrs, addr_nodes, Amount::from_sat(amount));
68+
69+
macro_rules! sync_wallets {
70+
() => {
71+
nodes.iter().for_each(|node| node.sync_wallets().unwrap())
72+
};
73+
}
74+
sync_wallets!();
75+
nodes.iter().for_each(|node| {
76+
assert_eq!(node.list_balances().spendable_onchain_balance_sats, amount);
77+
assert_eq!(node.list_balances().total_onchain_balance_sats, amount);
78+
});
79+
80+
81+
let mut nodes_funding_tx = HashMap::new();
82+
let funding_amount_sat = 2_000_000;
83+
for index in 0..nodes.len() {
84+
let node = &nodes[index];
85+
let next_node = if index >= nodes.len() - 1 { &nodes[0] } else { &nodes[index + 1] };
86+
87+
let funding_txo_b = open_channel(node, next_node, funding_amount_sat, true, electrsd);
88+
nodes_funding_tx.insert(node.node_id(), funding_txo_b);
89+
}
90+
91+
generate_blocks_and_wait(bitcoind, electrs, 6);
92+
sync_wallets!();
93+
94+
reorg!(reorg_depth);
95+
sync_wallets!();
96+
97+
macro_rules! collect_channel_ready_events {
98+
($node:expr, $expected:expr) => {{
99+
let mut user_channels = HashMap::new();
100+
for _ in 0..$expected {
101+
match $node.wait_next_event() {
102+
Event::ChannelReady { user_channel_id, counterparty_node_id, .. } => {
103+
$node.event_handled().unwrap();
104+
user_channels.insert(counterparty_node_id, user_channel_id);
105+
},
106+
other => panic!("Unexpected event: {:?}", other),
107+
}
108+
}
109+
user_channels
110+
}};
111+
}
112+
113+
let mut node_channels_id = HashMap::new();
114+
for index in 0..nodes.len() {
115+
let node = &nodes[index];
116+
117+
assert_eq!(
118+
node
119+
.list_payments_with_filter(|p| p.direction == PaymentDirection::Outbound
120+
&& matches!(p.kind, PaymentKind::Onchain { .. }))
121+
.len(),
122+
1
123+
);
124+
125+
let user_channels = collect_channel_ready_events!(node, 2);
126+
let next_node = if index >= nodes.len() - 1 { &nodes[0] } else { &nodes[index + 1] };
127+
let prev_node = if index == 0 { &nodes[nodes.len() - 1] } else { &nodes[index - 1] };
128+
129+
assert!(user_channels.get(&Some(next_node.node_id())) != None);
130+
assert!(user_channels.get(&Some(prev_node.node_id())) != None);
131+
132+
let user_channel_id =
133+
user_channels.get(&Some(next_node.node_id())).expect("Missing user channel for node");
134+
node_channels_id.insert(node.node_id(), *user_channel_id);
135+
}
136+
137+
138+
for index in 0..nodes.len() {
139+
let node_a = &nodes[index];
140+
let node_b = if index >= nodes.len() - 1 { &nodes[0] } else { &nodes[index + 1] };
141+
142+
let user_channel_id = node_channels_id.get(&node_a.node_id()).expect("user channel id not exist");
143+
let funding = nodes_funding_tx.get(&node_a.node_id()).expect("Funding tx not exist");
144+
145+
if force_close {
146+
node_a.force_close_channel(&user_channel_id, node_b.node_id(), None).unwrap();
147+
} else {
148+
node_a.close_channel(&user_channel_id, node_b.node_id()).unwrap();
149+
}
150+
151+
expect_event!(node_a, ChannelClosed);
152+
expect_event!(node_b, ChannelClosed);
153+
154+
wait_for_outpoint_spend(electrs, *funding);
155+
}
156+
157+
reorg!(reorg_depth);
158+
sync_wallets!();
159+
160+
generate_blocks_and_wait(bitcoind, electrs, 1);
161+
sync_wallets!();
162+
163+
if force_close {
164+
nodes.iter().for_each(|node| {
165+
node.sync_wallets().unwrap();
166+
// If there is no more balance, there is nothing to process here.
167+
if node.list_balances().lightning_balances.len() < 1 {
168+
return;
169+
}
170+
match node.list_balances().lightning_balances[0] {
171+
LightningBalance::ClaimableAwaitingConfirmations {
172+
confirmation_height,
173+
..
174+
} => {
175+
let cur_height = node.status().current_best_block.height;
176+
let blocks_to_go = confirmation_height - cur_height;
177+
generate_blocks_and_wait(bitcoind, electrs, blocks_to_go as usize);
178+
node.sync_wallets().unwrap();
179+
},
180+
_ => panic!("Unexpected balance state for node_hub!"),
181+
}
182+
183+
assert!(node.list_balances().lightning_balances.len() < 2);
184+
185+
assert!(node.list_balances().pending_balances_from_channel_closures.len() > 0);
186+
match node.list_balances().pending_balances_from_channel_closures[0] {
187+
PendingSweepBalance::BroadcastAwaitingConfirmation { .. } => {},
188+
_ => println!("Unexpected balance state!"),
189+
}
190+
191+
generate_blocks_and_wait(&bitcoind, electrs, 1);
192+
node.sync_wallets().unwrap();
193+
assert!(node.list_balances().lightning_balances.len() < 2);
194+
assert!(node.list_balances().pending_balances_from_channel_closures.len() > 0);
195+
match node.list_balances().pending_balances_from_channel_closures[0] {
196+
PendingSweepBalance::AwaitingThresholdConfirmations { .. } => {},
197+
_ => println!("Unexpected balance state!"),
198+
}
199+
});
200+
}
201+
202+
generate_blocks_and_wait(bitcoind, electrs, 6);
203+
sync_wallets!();
204+
205+
reorg!(reorg_depth);
206+
sync_wallets!();
207+
208+
// Check balance after close channel
209+
nodes.iter().for_each(|node| {
210+
assert!(node.list_balances().spendable_onchain_balance_sats > amount - 7000);
211+
assert!(node.list_balances().spendable_onchain_balance_sats < amount);
212+
213+
assert_eq!(node.list_balances().total_anchor_channels_reserve_sats, 0);
214+
assert!(node.list_balances().lightning_balances.is_empty());
215+
216+
assert_eq!(node.next_event(), None);
217+
});
218+
}
219+
}

0 commit comments

Comments
 (0)