Skip to content

Commit 86cc3d2

Browse files
authored
Merge pull request #604 from moisesPompilio/issue-575
Add reorg test
2 parents 6bf414f + e57927a commit 86cc3d2

File tree

2 files changed

+226
-5
lines changed

2 files changed

+226
-5
lines changed

tests/common/mod.rs

Lines changed: 33 additions & 5 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,
@@ -474,18 +491,27 @@ pub(crate) fn premine_and_distribute_funds<E: ElectrumApi>(
474491
let _ = bitcoind.load_wallet("ldk_node_test");
475492
generate_blocks_and_wait(bitcoind, electrs, 101);
476493

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-
}
494+
let amounts: HashMap<String, f64> =
495+
addrs.iter().map(|addr| (addr.to_string(), amount.to_btc())).collect();
496+
497+
let empty_account = json!("");
498+
let amounts_json = json!(amounts);
499+
let txid = bitcoind
500+
.call::<Value>("sendmany", &[empty_account, amounts_json])
501+
.unwrap()
502+
.as_str()
503+
.unwrap()
504+
.parse()
505+
.unwrap();
481506

507+
wait_for_tx(electrs, txid);
482508
generate_blocks_and_wait(bitcoind, electrs, 1);
483509
}
484510

485511
pub fn open_channel(
486512
node_a: &TestNode, node_b: &TestNode, funding_amount_sat: u64, should_announce: bool,
487513
electrsd: &ElectrsD,
488-
) {
514+
) -> OutPoint {
489515
if should_announce {
490516
node_a
491517
.open_announced_channel(
@@ -513,6 +539,8 @@ pub fn open_channel(
513539
let funding_txo_b = expect_channel_pending_event!(node_b, node_a.node_id());
514540
assert_eq!(funding_txo_a, funding_txo_b);
515541
wait_for_tx(&electrsd.client, funding_txo_a.txid);
542+
543+
funding_txo_a
516544
}
517545

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

tests/reorg_test.rs

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

0 commit comments

Comments
 (0)