Skip to content

Commit 8add429

Browse files
author
Antoine Riard
committed
Add test_static_spendable_outputs_preimage_tx
Aims to covered both keysinterace preimage tx case and detection of second remote commitment tx Add AddressType to describe DynamicOutput
1 parent 1b33064 commit 8add429

File tree

4 files changed

+209
-37
lines changed

4 files changed

+209
-37
lines changed

src/chain/keysinterface.rs

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,17 @@ use std::time::{SystemTime, UNIX_EPOCH};
2525
use std::sync::Arc;
2626
use std::sync::atomic::{AtomicUsize, Ordering};
2727

28+
/// Used to describe the type of address to which a DynamicOutput commits
29+
pub enum AddressType {
30+
/// Output commits to P2WSH
31+
P2WSH {
32+
/// witness_script needed to redeem it
33+
witness_script: Script,
34+
},
35+
/// Output commits to a P2WPKH
36+
P2WPKH,
37+
}
38+
2839
/// When on-chain outputs are created by rust-lightning an event is generated which informs the
2940
/// user thereof. This enum describes the format of the output and provides the OutPoint.
3041
pub enum SpendableOutputDescriptor {
@@ -37,17 +48,21 @@ pub enum SpendableOutputDescriptor {
3748
/// The output which is referenced by the given outpoint
3849
output: TxOut,
3950
},
40-
/// Outpoint commits to a P2WSH, should be spend by the following witness :
51+
/// Outpoint commits to a P2WSH if witness_script is Some or P2WPKH if it's None.
52+
/// P2WSH should be spend by the following witness :
4153
/// <local_delayedsig> 0 <witnessScript>
4254
/// With input nSequence set to_self_delay.
43-
/// Outputs from a HTLC-Success/Timeout tx
55+
/// P2WPKH should be spend by the following witness :
56+
/// <local_sig> <local_pubkey>
57+
/// Outputs from a HTLC-Success/Timeout tx/commitment tx
4458
DynamicOutput {
4559
/// Outpoint spendable by user wallet
4660
outpoint: OutPoint,
47-
/// local_delayedkey = delayed_payment_basepoint_secret + SHA256(per_commitment_point || delayed_payment_basepoint)
48-
local_delayedkey: SecretKey,
49-
/// witness redeemScript encumbering output
50-
witness_script: Script,
61+
/// local_delayedkey = delayed_payment_basepoint_secret + SHA256(per_commitment_point || delayed_payment_basepoint) OR
62+
/// localkey = payment_basepoint_secret + SHA256(per_commitment_point || payment_basepoint
63+
key: SecretKey,
64+
/// witness redeemScript encumbering output. If None script is a P2WPKH to build from key.
65+
address: AddressType,
5166
/// nSequence input must commit to self_delay to satisfy script's OP_CSV
5267
to_self_delay: u16,
5368
/// The output which is referenced by the given outpoint

src/ln/channel.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -436,7 +436,7 @@ impl Channel {
436436

437437
let secp_ctx = Secp256k1::new();
438438
let channel_monitor = ChannelMonitor::new(&chan_keys.revocation_base_key, &chan_keys.delayed_payment_base_key,
439-
&chan_keys.htlc_base_key, BREAKDOWN_TIMEOUT,
439+
&chan_keys.htlc_base_key, &chan_keys.payment_base_key, BREAKDOWN_TIMEOUT,
440440
keys_provider.get_destination_script(), logger.clone());
441441

442442
Ok(Channel {
@@ -624,7 +624,7 @@ impl Channel {
624624

625625
let secp_ctx = Secp256k1::new();
626626
let mut channel_monitor = ChannelMonitor::new(&chan_keys.revocation_base_key, &chan_keys.delayed_payment_base_key,
627-
&chan_keys.htlc_base_key, BREAKDOWN_TIMEOUT,
627+
&chan_keys.htlc_base_key, &chan_keys.payment_base_key, BREAKDOWN_TIMEOUT,
628628
keys_provider.get_destination_script(), logger.clone());
629629
channel_monitor.set_their_base_keys(&msg.htlc_basepoint, &msg.delayed_payment_basepoint);
630630
channel_monitor.provide_their_next_revocation_point(Some((INITIAL_COMMITMENT_NUMBER, msg.first_per_commitment_point)));

src/ln/channelmanager.rs

Lines changed: 116 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3209,7 +3209,7 @@ mod tests {
32093209
use chain::chaininterface;
32103210
use chain::transaction::OutPoint;
32113211
use chain::chaininterface::{ChainListener, ChainWatchInterface};
3212-
use chain::keysinterface::{KeysInterface, SpendableOutputDescriptor};
3212+
use chain::keysinterface::{KeysInterface, SpendableOutputDescriptor, AddressType};
32133213
use chain::keysinterface;
32143214
use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,OnionKeys,PaymentFailReason,RAACommitmentOrder};
32153215
use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, ManyChannelMonitor};
@@ -3225,6 +3225,8 @@ mod tests {
32253225

32263226
use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
32273227
use bitcoin::util::bip143;
3228+
use bitcoin::util::address::Address;
3229+
use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
32283230
use bitcoin::blockdata::block::{Block, BlockHeader};
32293231
use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType};
32303232
use bitcoin::blockdata::script::{Builder, Script};
@@ -7546,7 +7548,7 @@ mod tests {
75467548
Event::SpendableOutputs { ref outputs } => {
75477549
for outp in outputs {
75487550
match *outp {
7549-
SpendableOutputDescriptor::DynamicOutput { ref outpoint, ref local_delayedkey, ref witness_script, ref to_self_delay, ref output } => {
7551+
SpendableOutputDescriptor::DynamicOutput { ref outpoint, ref key, ref address, ref to_self_delay, ref output } => {
75507552
let input = TxIn {
75517553
previous_output: outpoint.clone(),
75527554
script_sig: Script::new(),
@@ -7563,14 +7565,28 @@ mod tests {
75637565
input: vec![input],
75647566
output: vec![outp],
75657567
};
7566-
let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
75677568
let secp_ctx = Secp256k1::new();
7568-
let local_delaysig = secp_ctx.sign(&sighash, local_delayedkey);
7569-
spend_tx.input[0].witness.push(local_delaysig.serialize_der(&secp_ctx).to_vec());
7570-
spend_tx.input[0].witness[0].push(SigHashType::All as u8);
7571-
spend_tx.input[0].witness.push(vec!(0));
7572-
spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
7573-
txn.push(spend_tx);
7569+
match *address {
7570+
AddressType::P2WSH { ref witness_script } => {
7571+
let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
7572+
let local_delaysig = secp_ctx.sign(&sighash, key);
7573+
spend_tx.input[0].witness.push(local_delaysig.serialize_der(&secp_ctx).to_vec());
7574+
spend_tx.input[0].witness[0].push(SigHashType::All as u8);
7575+
spend_tx.input[0].witness.push(vec!(0));
7576+
spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
7577+
txn.push(spend_tx);
7578+
},
7579+
AddressType::P2WPKH => {
7580+
let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
7581+
let witness_script = Address::p2pkh(&remotepubkey, Network::Testnet).script_pubkey();
7582+
let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
7583+
let remotesig = secp_ctx.sign(&sighash, key);
7584+
spend_tx.input[0].witness.push(remotesig.serialize_der(&secp_ctx).to_vec());
7585+
spend_tx.input[0].witness[0].push(SigHashType::All as u8);
7586+
spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
7587+
txn.push(spend_tx);
7588+
},
7589+
}
75747590
},
75757591
_ => panic!("Unexpected event"),
75767592
}
@@ -7584,6 +7600,57 @@ mod tests {
75847600
}
75857601
}
75867602

7603+
macro_rules! check_static_output {
7604+
($event: expr, $node: expr, $event_idx: expr, $output_idx: expr, $der_idx: expr, $idx_node: expr) => {
7605+
match $event[$event_idx] {
7606+
Event::SpendableOutputs { ref outputs } => {
7607+
match outputs[$output_idx] {
7608+
SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
7609+
let secp_ctx = Secp256k1::new();
7610+
let input = TxIn {
7611+
previous_output: outpoint.clone(),
7612+
script_sig: Script::new(),
7613+
sequence: 0,
7614+
witness: Vec::new(),
7615+
};
7616+
let outp = TxOut {
7617+
script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
7618+
value: output.value,
7619+
};
7620+
let mut spend_tx = Transaction {
7621+
version: 2,
7622+
lock_time: 0,
7623+
input: vec![input],
7624+
output: vec![outp.clone()],
7625+
};
7626+
let secret = {
7627+
match ExtendedPrivKey::new_master(&secp_ctx, Network::Testnet, &$node[$idx_node].node_seed) {
7628+
Ok(master_key) => {
7629+
match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx)) {
7630+
Ok(key) => key,
7631+
Err(_) => panic!("Your RNG is busted"),
7632+
}
7633+
}
7634+
Err(_) => panic!("Your rng is busted"),
7635+
}
7636+
};
7637+
let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
7638+
let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
7639+
let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
7640+
let sig = secp_ctx.sign(&sighash, &secret.secret_key);
7641+
spend_tx.input[0].witness.push(sig.serialize_der(&secp_ctx).to_vec());
7642+
spend_tx.input[0].witness[0].push(SigHashType::All as u8);
7643+
spend_tx.input[0].witness.push(pubkey.serialize().to_vec());
7644+
spend_tx
7645+
},
7646+
_ => panic!("Unexpected event !"),
7647+
}
7648+
},
7649+
_ => panic!("Unexpected event !"),
7650+
};
7651+
}
7652+
}
7653+
75877654
#[test]
75887655
fn test_claim_sizeable_push_msat() {
75897656
// Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
@@ -7607,4 +7674,44 @@ mod tests {
76077674
assert_eq!(spend_txn.len(), 1);
76087675
check_spends!(spend_txn[0], node_txn[0].clone());
76097676
}
7677+
7678+
#[test]
7679+
fn test_static_spendable_outputs_preimage_tx() {
7680+
let nodes = create_network(2);
7681+
7682+
// Create some initial channels
7683+
let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
7684+
7685+
let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7686+
7687+
let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
7688+
assert_eq!(commitment_tx[0].input.len(), 1);
7689+
assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
7690+
7691+
// Settle A's commitment tx on B's chain
7692+
let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7693+
assert!(nodes[1].node.claim_funds(payment_preimage));
7694+
check_added_monitors!(nodes[1], 1);
7695+
nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
7696+
let events = nodes[1].node.get_and_clear_pending_msg_events();
7697+
match events[0] {
7698+
MessageSendEvent::UpdateHTLCs { .. } => {},
7699+
_ => panic!("Unexpected event"),
7700+
}
7701+
match events[1] {
7702+
MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7703+
_ => panic!("Unexepected event"),
7704+
}
7705+
7706+
// Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
7707+
let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 1 (local commitment tx), ChannelMonitor: 2 (1 preimage tx) * 2 (block-rescan)
7708+
check_spends!(node_txn[0], commitment_tx[0].clone());
7709+
assert_eq!(node_txn[0], node_txn[2]);
7710+
assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 133);
7711+
check_spends!(node_txn[1], chan_1.3.clone());
7712+
7713+
let events = nodes[1].chan_monitor.simple_monitor.get_and_clear_pending_events();
7714+
let spend_tx = check_static_output!(events, nodes, 0, 0, 1, 1);
7715+
check_spends!(spend_tx, node_txn[0].clone());
7716+
}
76107717
}

0 commit comments

Comments
 (0)