Skip to content

Commit 7e3dd9a

Browse files
committed
Test justice tx formation from persistence
Here we implement `WatchtowerPersister`, which provides a test-only sample implementation of `Persist` similar to how we might imagine a user to build watchtower-like functionality in the persistence pipeline. We test that the `WatchtowerPersister` is able to successfully build and sign a valid justice transaction that sweeps a counterparty's funds if they broadcast an old commitment.
1 parent 782c576 commit 7e3dd9a

File tree

3 files changed

+164
-4
lines changed

3 files changed

+164
-4
lines changed

lightning/src/ln/functional_test_utils.rs

+6-2
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
//! A bunch of useful utilities for building networks of nodes and exchanging messages between
1111
//! nodes for functional tests.
1212
13-
use crate::chain::{BestBlock, ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
13+
use crate::chain::{BestBlock, ChannelMonitorUpdateStatus, Confirm, Listen, Watch, chainmonitor::Persist};
1414
use crate::sign::EntropySource;
1515
use crate::chain::channelmonitor::ChannelMonitor;
1616
use crate::chain::transaction::OutPoint;
@@ -2556,10 +2556,14 @@ pub fn create_chanmon_cfgs(node_count: usize) -> Vec<TestChanMonCfg> {
25562556
}
25572557

25582558
pub fn create_node_cfgs<'a>(node_count: usize, chanmon_cfgs: &'a Vec<TestChanMonCfg>) -> Vec<NodeCfg<'a>> {
2559+
create_node_cfgs_with_persisters(node_count, chanmon_cfgs, chanmon_cfgs.iter().map(|c| &c.persister).collect())
2560+
}
2561+
2562+
pub fn create_node_cfgs_with_persisters<'a>(node_count: usize, chanmon_cfgs: &'a Vec<TestChanMonCfg>, persisters: Vec<&'a impl Persist<EnforcingSigner>>) -> Vec<NodeCfg<'a>> {
25592563
let mut nodes = Vec::new();
25602564

25612565
for i in 0..node_count {
2562-
let chain_monitor = test_utils::TestChainMonitor::new(Some(&chanmon_cfgs[i].chain_source), &chanmon_cfgs[i].tx_broadcaster, &chanmon_cfgs[i].logger, &chanmon_cfgs[i].fee_estimator, &chanmon_cfgs[i].persister, &chanmon_cfgs[i].keys_manager);
2566+
let chain_monitor = test_utils::TestChainMonitor::new(Some(&chanmon_cfgs[i].chain_source), &chanmon_cfgs[i].tx_broadcaster, &chanmon_cfgs[i].logger, &chanmon_cfgs[i].fee_estimator, persisters[i], &chanmon_cfgs[i].keys_manager);
25632567
let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[i].logger));
25642568
let seed = [i as u8; 32];
25652569
nodes.push(NodeCfg {

lightning/src/ln/functional_tests.rs

+66-2
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use crate::chain::chaininterface::LowerBoundedFeeEstimator;
1717
use crate::chain::channelmonitor;
1818
use crate::chain::channelmonitor::{CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
1919
use crate::chain::transaction::OutPoint;
20-
use crate::sign::{ChannelSigner, EcdsaChannelSigner, EntropySource};
20+
use crate::sign::{ChannelSigner, EcdsaChannelSigner, EntropySource, SignerProvider};
2121
use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, ClosureReason, HTLCDestination, PaymentFailureReason};
2222
use crate::ln::{PaymentPreimage, PaymentSecret, PaymentHash};
2323
use crate::ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT, get_holder_selected_channel_reserve_satoshis, OutboundV1Channel, InboundV1Channel};
@@ -31,7 +31,7 @@ use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, NodeFeatures};
3131
use crate::ln::msgs;
3232
use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
3333
use crate::util::enforcing_trait_impls::EnforcingSigner;
34-
use crate::util::test_utils;
34+
use crate::util::test_utils::{self, WatchtowerPersister};
3535
use crate::util::errors::APIError;
3636
use crate::util::ser::{Writeable, ReadableArgs};
3737
use crate::util::string::UntrustedString;
@@ -2549,6 +2549,70 @@ fn revoked_output_claim() {
25492549
check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
25502550
}
25512551

2552+
#[test]
2553+
fn test_forming_justice_tx_from_monitor_updates() {
2554+
do_test_forming_justice_tx_from_monitor_updates(true);
2555+
do_test_forming_justice_tx_from_monitor_updates(false);
2556+
}
2557+
2558+
fn do_test_forming_justice_tx_from_monitor_updates(broadcast_initial_commitment: bool) {
2559+
// Simple test to make sure that the justice tx formed in WatchtowerPersister
2560+
// is properly formed and can be broadcasted/confirmed successfully in the event
2561+
// that a revoked commitment transaction is broadcasted
2562+
// (Similar to `revoked_output_claim` test but we get the justice tx + broadcast manually)
2563+
let chanmon_cfgs = create_chanmon_cfgs(2);
2564+
let destination_script0 = chanmon_cfgs[0].keys_manager.get_destination_script().unwrap();
2565+
let destination_script1 = chanmon_cfgs[1].keys_manager.get_destination_script().unwrap();
2566+
let persisters = vec![WatchtowerPersister::new(destination_script0),
2567+
WatchtowerPersister::new(destination_script1)];
2568+
let node_cfgs = create_node_cfgs_with_persisters(2, &chanmon_cfgs, persisters.iter().collect());
2569+
let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2570+
let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2571+
let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
2572+
let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
2573+
2574+
if !broadcast_initial_commitment {
2575+
// Send a payment to move the channel forward
2576+
send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2577+
}
2578+
2579+
// node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output.
2580+
// We'll keep this commitment transaction to broadcast once it's revoked.
2581+
let revoked_local_txn = get_local_commitment_txn!(nodes[0], channel_id);
2582+
assert_eq!(revoked_local_txn.len(), 1);
2583+
let revoked_commitment_tx = &revoked_local_txn[0];
2584+
2585+
// Send another payment, now revoking the previous commitment tx
2586+
send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2587+
2588+
let justice_tx = persisters[1].justice_tx(funding_txo, &revoked_commitment_tx.txid()).unwrap();
2589+
check_spends!(justice_tx, revoked_commitment_tx);
2590+
2591+
mine_transactions(&nodes[1], &[revoked_commitment_tx, &justice_tx]);
2592+
mine_transactions(&nodes[0], &[revoked_commitment_tx, &justice_tx]);
2593+
2594+
check_added_monitors!(nodes[1], 1);
2595+
check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2596+
get_announce_close_broadcast_events(&nodes, 1, 0);
2597+
2598+
check_added_monitors!(nodes[0], 1);
2599+
check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2600+
2601+
// Check that the justice tx has sent the revoked output value to nodes[1]
2602+
let monitor = get_monitor!(nodes[1], channel_id);
2603+
let total_claimable_balance = monitor.get_claimable_balances().iter().fold(0, |sum, balance| {
2604+
match balance {
2605+
channelmonitor::Balance::ClaimableAwaitingConfirmations { claimable_amount_satoshis, .. } => sum + claimable_amount_satoshis,
2606+
_ => panic!("Unexpected balance type"),
2607+
}
2608+
});
2609+
// On the first commitment, node[1]'s balance was below dust so it didn't have an output
2610+
let node1_channel_balance = if broadcast_initial_commitment { 0 } else { revoked_commitment_tx.output[0].value };
2611+
let expected_claimable_balance = node1_channel_balance + justice_tx.output[0].value;
2612+
assert_eq!(total_claimable_balance, expected_claimable_balance);
2613+
}
2614+
2615+
25522616
#[test]
25532617
fn claim_htlc_outputs_shared_tx() {
25542618
// Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx

lightning/src/util/test_utils.rs

+92
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,17 @@ use crate::chain;
1111
use crate::chain::WatchedOutput;
1212
use crate::chain::chaininterface;
1313
use crate::chain::chaininterface::ConfirmationTarget;
14+
use crate::chain::chaininterface::FEERATE_FLOOR_SATS_PER_KW;
1415
use crate::chain::chainmonitor;
1516
use crate::chain::chainmonitor::MonitorUpdateId;
1617
use crate::chain::channelmonitor;
1718
use crate::chain::channelmonitor::MonitorEvent;
19+
use crate::chain::package::WEIGHT_REVOKED_OUTPUT;
1820
use crate::chain::transaction::OutPoint;
1921
use crate::sign;
2022
use crate::events;
2123
use crate::ln::channelmanager;
24+
use crate::ln::chan_utils::CommitmentTransaction;
2225
use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
2326
use crate::ln::{msgs, wire};
2427
use crate::ln::msgs::LightningError;
@@ -266,6 +269,95 @@ impl<'a> chain::Watch<EnforcingSigner> for TestChainMonitor<'a> {
266269
}
267270
}
268271

272+
pub(crate) struct WatchtowerPersister {
273+
persister: TestPersister,
274+
/// Upon a new commitment_signed, we'll get a
275+
/// ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTxInfo. We'll store the commitment
276+
/// tx so we can build the justice tx after our counterparty revokes it.
277+
counterparty_commitment_txs: Mutex<HashMap<OutPoint, VecDeque<CommitmentTransaction>>>,
278+
/// After receiving a revoke_and_ack for a commitment number, we'll form and store the justice
279+
/// tx which would be used to provide a watchtower with the data it needs.
280+
watchtower_state: Mutex<HashMap<OutPoint, HashMap<Txid, Transaction>>>,
281+
destination_script: Script,
282+
}
283+
284+
impl WatchtowerPersister {
285+
pub(crate) fn new(destination_script: Script) -> Self {
286+
WatchtowerPersister {
287+
persister: TestPersister::new(),
288+
counterparty_commitment_txs: Mutex::new(HashMap::new()),
289+
watchtower_state: Mutex::new(HashMap::new()),
290+
destination_script,
291+
}
292+
}
293+
294+
pub(crate) fn justice_tx(&self, funding_txo: OutPoint, commitment_txid: &Txid) -> Option<Transaction> {
295+
self.watchtower_state.lock().unwrap().get(&funding_txo).unwrap().get(commitment_txid).cloned()
296+
}
297+
}
298+
299+
impl<Signer: sign::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> for WatchtowerPersister {
300+
fn persist_new_channel(&self, funding_txo: OutPoint, data: &channelmonitor::ChannelMonitor<Signer>, id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
301+
assert!(self.counterparty_commitment_txs.lock().unwrap()
302+
.insert(funding_txo, VecDeque::new()).is_none());
303+
assert!(self.watchtower_state.lock().unwrap()
304+
.insert(funding_txo, HashMap::new()).is_none());
305+
306+
let initial_counterparty_commitment_tx = data.initial_counterparty_commitment_tx()
307+
.expect("First and only call expects Some");
308+
self.counterparty_commitment_txs.lock().unwrap().get_mut(&funding_txo).unwrap().push_back(initial_counterparty_commitment_tx);
309+
310+
self.persister.persist_new_channel(funding_txo, data, id)
311+
}
312+
313+
fn update_persisted_channel(&self, funding_txo: OutPoint, update: Option<&channelmonitor::ChannelMonitorUpdate>, data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
314+
if let Some(update) = update {
315+
// Track new counterparty commitment txs
316+
let commitment_txs = data.counterparty_commitment_txs_from_update(update);
317+
let mut channels_counterparty_commitments = self.counterparty_commitment_txs.lock().unwrap();
318+
let channel_state = channels_counterparty_commitments.get_mut(&funding_txo).unwrap();
319+
channel_state.extend(commitment_txs.into_iter());
320+
321+
// Form justice txs from revoked counterparty commitment txs
322+
while let Some(counterparty_commitment_tx) = channel_state.front() {
323+
let trusted_tx = counterparty_commitment_tx.trust();
324+
let built_tx = trusted_tx.built_transaction();
325+
let output_idx = match counterparty_commitment_tx.revokeable_output_index() {
326+
Some(idx) => idx,
327+
None => {
328+
channel_state.pop_front();
329+
continue;
330+
}
331+
};
332+
333+
let value = built_tx.transaction.output[output_idx as usize].value;
334+
let mut justice_tx = counterparty_commitment_tx.build_justice_tx(
335+
output_idx as u32, value, self.destination_script.clone());
336+
337+
let weight = justice_tx.weight() as u64 + WEIGHT_REVOKED_OUTPUT;
338+
let min_feerate_per_kw = FEERATE_FLOOR_SATS_PER_KW;
339+
let fee = min_feerate_per_kw as u64 * weight / 1000;
340+
justice_tx.output[0].value -= fee;
341+
342+
let input_idx = 0;
343+
let commitment_number = counterparty_commitment_tx.commitment_number();
344+
let commitment_txid = built_tx.txid;
345+
match data.sign_justice_tx(justice_tx, input_idx, value, commitment_number) {
346+
Ok(signed_justice_tx) => {
347+
let dup = self.watchtower_state.lock().unwrap()
348+
.get_mut(&funding_txo).unwrap()
349+
.insert(commitment_txid, signed_justice_tx);
350+
assert!(dup.is_none());
351+
channel_state.pop_front();
352+
},
353+
Err(_) => break,
354+
}
355+
}
356+
}
357+
self.persister.update_persisted_channel(funding_txo, update, data, update_id)
358+
}
359+
}
360+
269361
pub struct TestPersister {
270362
/// The queue of update statuses we'll return. If none are queued, ::Completed will always be
271363
/// returned.

0 commit comments

Comments
 (0)