Skip to content

Commit 444897d

Browse files
add reorg test
feat: #575
1 parent d2cadd0 commit 444897d

File tree

2 files changed

+272
-9
lines changed

2 files changed

+272
-9
lines changed

tests/common/mod.rs

Lines changed: 54 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,12 @@ use lightning_types::payment::{PaymentHash, PaymentPreimage};
2929

3030
use lightning_persister::fs_store::FilesystemStore;
3131

32+
use bitcoin::hashes::hex::FromHex;
3233
use bitcoin::hashes::sha256::Hash as Sha256;
3334
use bitcoin::hashes::Hash;
34-
use bitcoin::{Address, Amount, Network, OutPoint, Txid};
35+
use bitcoin::{
36+
Address, Amount, Network, OutPoint, ScriptBuf, Sequence, Transaction, Txid, Witness,
37+
};
3538

3639
use electrsd::corepc_node::Client as BitcoindClient;
3740
use electrsd::corepc_node::Node as BitcoinD;
@@ -40,7 +43,10 @@ use electrum_client::ElectrumApi;
4043

4144
use rand::distributions::Alphanumeric;
4245
use rand::{thread_rng, Rng};
46+
use serde_json::{json, Value};
4347

48+
use std::collections::HashMap;
49+
use std::collections::HashSet;
4450
use std::env;
4551
use std::path::PathBuf;
4652
use std::sync::{Arc, RwLock};
@@ -395,6 +401,21 @@ pub(crate) fn generate_blocks_and_wait<E: ElectrumApi>(
395401
println!("\n");
396402
}
397403

404+
pub(crate) fn invalidate_blocks(bitcoind: &BitcoindClient, num_blocks: usize) {
405+
let blockchain_info = bitcoind.get_blockchain_info().expect("failed to get blockchain info");
406+
let cur_height = blockchain_info.blocks as usize;
407+
let target_height = cur_height - num_blocks + 1;
408+
let block_hash = bitcoind
409+
.get_block_hash(target_height as u64)
410+
.expect("failed to get block hash")
411+
.block_hash()
412+
.expect("block hash should be present");
413+
bitcoind.invalidate_block(block_hash).expect("failed to invalidate block");
414+
let blockchain_info = bitcoind.get_blockchain_info().expect("failed to get blockchain info");
415+
let new_cur_height = blockchain_info.blocks as usize;
416+
assert!(new_cur_height + num_blocks == cur_height);
417+
}
418+
398419
pub(crate) fn wait_for_block<E: ElectrumApi>(electrs: &E, min_height: usize) {
399420
let mut header = match electrs.block_headers_subscribe() {
400421
Ok(header) => header,
@@ -467,25 +488,47 @@ where
467488
}
468489
}
469490

470-
pub(crate) fn premine_and_distribute_funds<E: ElectrumApi>(
471-
bitcoind: &BitcoindClient, electrs: &E, addrs: Vec<Address>, amount: Amount,
472-
) {
491+
pub(crate) fn premine_blocks<E: ElectrumApi>(bitcoind: &BitcoindClient, electrs: &E) {
473492
let _ = bitcoind.create_wallet("ldk_node_test");
474493
let _ = bitcoind.load_wallet("ldk_node_test");
475494
generate_blocks_and_wait(bitcoind, electrs, 101);
476-
477-
for addr in addrs {
478-
let txid = bitcoind.send_to_address(&addr, amount).unwrap().0.parse().unwrap();
479-
wait_for_tx(electrs, txid);
495+
}
496+
pub(crate) fn distribute_funds<E: ElectrumApi>(
497+
bitcoind: &BitcoindClient, electrs: &E, addrs: Vec<Address>, amount: Amount,
498+
) -> Txid {
499+
let mut amounts = HashMap::<String, f64>::new();
500+
for addr in &addrs {
501+
amounts.insert(addr.to_string(), amount.to_btc());
480502
}
481503

504+
let empty_account = json!("");
505+
let amounts_json = json!(amounts);
506+
let txid = bitcoind
507+
.call::<Value>("sendmany", &[empty_account, amounts_json])
508+
.unwrap()
509+
.as_str()
510+
.unwrap()
511+
.parse()
512+
.unwrap();
513+
514+
wait_for_tx(electrs, txid);
482515
generate_blocks_and_wait(bitcoind, electrs, 1);
516+
517+
txid
518+
}
519+
520+
pub(crate) fn premine_and_distribute_funds<E: ElectrumApi>(
521+
bitcoind: &BitcoindClient, electrs: &E, addrs: Vec<Address>, amount: Amount,
522+
) {
523+
premine_blocks(bitcoind, electrs);
524+
525+
distribute_funds(bitcoind, electrs, addrs, amount);
483526
}
484527

485528
pub fn open_channel(
486529
node_a: &TestNode, node_b: &TestNode, funding_amount_sat: u64, should_announce: bool,
487530
electrsd: &ElectrsD,
488-
) {
531+
) -> OutPoint {
489532
if should_announce {
490533
node_a
491534
.open_announced_channel(
@@ -513,6 +556,8 @@ pub fn open_channel(
513556
let funding_txo_b = expect_channel_pending_event!(node_b, node_a.node_id());
514557
assert_eq!(funding_txo_a, funding_txo_b);
515558
wait_for_tx(&electrsd.client, funding_txo_a.txid);
559+
560+
funding_txo_a
516561
}
517562

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

tests/prop_test.rs

Lines changed: 218 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,218 @@
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 test_reorg(
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+
reorg!(reorg_depth);
94+
sync_wallets!();
95+
96+
macro_rules! collect_channel_ready_events {
97+
($node:expr, $expected:expr) => {{
98+
let mut user_channels = HashMap::new();
99+
for _ in 0..$expected {
100+
match $node.wait_next_event() {
101+
Event::ChannelReady { user_channel_id, counterparty_node_id, .. } => {
102+
$node.event_handled().unwrap();
103+
user_channels.insert(counterparty_node_id, user_channel_id);
104+
},
105+
other => panic!("Unexpected event: {:?}", other),
106+
}
107+
}
108+
user_channels
109+
}};
110+
}
111+
112+
let mut node_channels_id = HashMap::new();
113+
for index in 0..nodes.len() {
114+
let node = &nodes[index];
115+
116+
assert_eq!(
117+
node
118+
.list_payments_with_filter(|p| p.direction == PaymentDirection::Outbound
119+
&& matches!(p.kind, PaymentKind::Onchain { .. }))
120+
.len(),
121+
1
122+
);
123+
124+
let user_channels = collect_channel_ready_events!(node, 2);
125+
let next_node = if index >= nodes.len() - 1 { &nodes[0] } else { &nodes[index + 1] };
126+
let prev_node = if index == 0 { &nodes[nodes.len() - 1] } else { &nodes[index - 1] };
127+
128+
assert!(user_channels.get(&Some(next_node.node_id())) != None);
129+
assert!(user_channels.get(&Some(prev_node.node_id())) != None);
130+
131+
let user_channel_id =
132+
user_channels.get(&Some(next_node.node_id())).expect("Missing user channel for node");
133+
node_channels_id.insert(node.node_id(), *user_channel_id);
134+
}
135+
136+
137+
for index in 0..nodes.len() {
138+
let node_a = &nodes[index];
139+
let node_b = if index >= nodes.len() - 1 { &nodes[0] } else { &nodes[index + 1] };
140+
141+
let user_channel_id = node_channels_id.get(&node_a.node_id()).expect("user channel id not exist");
142+
let funding = nodes_funding_tx.get(&node_a.node_id()).expect("Funding tx not exist");
143+
144+
if force_close {
145+
node_a.force_close_channel(&user_channel_id, node_b.node_id(), None).unwrap();
146+
} else {
147+
node_a.close_channel(&user_channel_id, node_b.node_id()).unwrap();
148+
}
149+
150+
expect_event!(node_a, ChannelClosed);
151+
expect_event!(node_b, ChannelClosed);
152+
153+
wait_for_outpoint_spend(electrs, *funding);
154+
}
155+
156+
reorg!(reorg_depth);
157+
sync_wallets!();
158+
159+
generate_blocks_and_wait(bitcoind, electrs, 1);
160+
sync_wallets!();
161+
162+
if force_close {
163+
nodes.iter().for_each(|node| {
164+
node.sync_wallets().unwrap();
165+
// If there is no more balance, there is nothing to process here.
166+
if node.list_balances().lightning_balances.len() < 1 {
167+
return;
168+
}
169+
match node.list_balances().lightning_balances[0] {
170+
LightningBalance::ClaimableAwaitingConfirmations {
171+
confirmation_height,
172+
..
173+
} => {
174+
let cur_height = node.status().current_best_block.height;
175+
let blocks_to_go = confirmation_height - cur_height;
176+
generate_blocks_and_wait(bitcoind, electrs, blocks_to_go as usize);
177+
node.sync_wallets().unwrap();
178+
},
179+
_ => panic!("Unexpected balance state for node_hub!"),
180+
}
181+
182+
assert!(node.list_balances().lightning_balances.len() < 2);
183+
184+
assert!(node.list_balances().pending_balances_from_channel_closures.len() > 0);
185+
match node.list_balances().pending_balances_from_channel_closures[0] {
186+
PendingSweepBalance::BroadcastAwaitingConfirmation { .. } => {},
187+
_ => println!("Unexpected balance state!"),
188+
}
189+
190+
generate_blocks_and_wait(&bitcoind, electrs, 1);
191+
node.sync_wallets().unwrap();
192+
assert!(node.list_balances().lightning_balances.len() < 2);
193+
assert!(node.list_balances().pending_balances_from_channel_closures.len() > 0);
194+
match node.list_balances().pending_balances_from_channel_closures[0] {
195+
PendingSweepBalance::AwaitingThresholdConfirmations { .. } => {},
196+
_ => println!("Unexpected balance state!"),
197+
}
198+
});
199+
}
200+
201+
generate_blocks_and_wait(bitcoind, electrs, 6);
202+
sync_wallets!();
203+
204+
reorg!(reorg_depth);
205+
sync_wallets!();
206+
207+
// Check balance after close channel
208+
nodes.iter().for_each(|node| {
209+
assert!(node.list_balances().spendable_onchain_balance_sats > amount - 7000);
210+
assert!(node.list_balances().spendable_onchain_balance_sats < amount);
211+
212+
assert_eq!(node.list_balances().total_anchor_channels_reserve_sats, 0);
213+
assert!(node.list_balances().lightning_balances.is_empty());
214+
215+
assert_eq!(node.next_event(), None);
216+
});
217+
}
218+
}

0 commit comments

Comments
 (0)