Skip to content

Commit 5e4096c

Browse files
committed
f - fix chanmon_consistency
1 parent 8530bbd commit 5e4096c

File tree

1 file changed

+42
-73
lines changed

1 file changed

+42
-73
lines changed

fuzz/src/chanmon_consistency.rs

Lines changed: 42 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
//! send-side handling is correct, other peers. We consider it a failure if any action results in a
1919
//! channel being force-closed.
2020
21+
use bitcoin::FeeRate;
2122
use bitcoin::amount::Amount;
2223
use bitcoin::constants::genesis_block;
2324
use bitcoin::locktime::absolute::LockTime;
@@ -43,6 +44,7 @@ use lightning::chain::{
4344
chainmonitor, channelmonitor, BestBlock, ChannelMonitorUpdateStatus, Confirm, Watch,
4445
};
4546
use lightning::events;
47+
use lightning::events::bump_transaction::sync::{WalletSourceSync, WalletSync};
4648
use lightning::ln::channel::{
4749
FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MAX_STD_OUTPUT_DUST_LIMIT_SATOSHIS,
4850
};
@@ -70,12 +72,14 @@ use lightning::sign::{
7072
SignerProvider,
7173
};
7274
use lightning::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
75+
use lightning::util::async_poll::{MaybeSend, MaybeSync};
7376
use lightning::util::config::UserConfig;
7477
use lightning::util::errors::APIError;
7578
use lightning::util::hash_tables::*;
7679
use lightning::util::logger::Logger;
7780
use lightning::util::ser::{LengthReadable, ReadableArgs, Writeable, Writer};
7881
use lightning::util::test_channel_signer::{EnforcementState, TestChannelSigner};
82+
use lightning::util::test_utils::TestWalletSource;
7983

8084
use lightning_invoice::RawBolt11Invoice;
8185

@@ -168,63 +172,6 @@ impl Writer for VecWriter {
168172
}
169173
}
170174

171-
pub struct TestWallet {
172-
secret_key: SecretKey,
173-
utxos: Mutex<Vec<lightning::events::bump_transaction::Utxo>>,
174-
secp: Secp256k1<bitcoin::secp256k1::All>,
175-
}
176-
177-
impl TestWallet {
178-
pub fn new(secret_key: SecretKey) -> Self {
179-
Self { secret_key, utxos: Mutex::new(Vec::new()), secp: Secp256k1::new() }
180-
}
181-
182-
fn get_change_script(&self) -> Result<ScriptBuf, ()> {
183-
let public_key = bitcoin::PublicKey::new(self.secret_key.public_key(&self.secp));
184-
Ok(ScriptBuf::new_p2wpkh(&public_key.wpubkey_hash().unwrap()))
185-
}
186-
187-
pub fn add_utxo(&self, outpoint: bitcoin::OutPoint, value: Amount) -> TxOut {
188-
let public_key = bitcoin::PublicKey::new(self.secret_key.public_key(&self.secp));
189-
let utxo = lightning::events::bump_transaction::Utxo::new_v0_p2wpkh(
190-
outpoint,
191-
value,
192-
&public_key.wpubkey_hash().unwrap(),
193-
);
194-
self.utxos.lock().unwrap().push(utxo.clone());
195-
utxo.output
196-
}
197-
198-
pub fn sign_tx(
199-
&self, mut tx: Transaction,
200-
) -> Result<Transaction, bitcoin::sighash::P2wpkhError> {
201-
let utxos = self.utxos.lock().unwrap();
202-
for i in 0..tx.input.len() {
203-
if let Some(utxo) =
204-
utxos.iter().find(|utxo| utxo.outpoint == tx.input[i].previous_output)
205-
{
206-
let sighash = bitcoin::sighash::SighashCache::new(&tx).p2wpkh_signature_hash(
207-
i,
208-
&utxo.output.script_pubkey,
209-
utxo.output.value,
210-
bitcoin::EcdsaSighashType::All,
211-
)?;
212-
let signature = self.secp.sign_ecdsa(
213-
&secp256k1::Message::from_digest(sighash.to_byte_array()),
214-
&self.secret_key,
215-
);
216-
let bitcoin_sig = bitcoin::ecdsa::Signature {
217-
signature,
218-
sighash_type: bitcoin::EcdsaSighashType::All,
219-
};
220-
tx.input[i].witness =
221-
bitcoin::Witness::p2wpkh(&bitcoin_sig, &self.secret_key.public_key(&self.secp));
222-
}
223-
}
224-
Ok(tx)
225-
}
226-
}
227-
228175
/// The LDK API requires that any time we tell it we're done persisting a `ChannelMonitor[Update]`
229176
/// we never pass it in as the "latest" `ChannelMonitor` on startup. However, we can pass
230177
/// out-of-date monitors as long as we never told LDK we finished persisting them, which we do by
@@ -532,7 +479,7 @@ type ChanMan<'a> = ChannelManager<
532479
Arc<FuzzEstimator>,
533480
&'a FuzzRouter,
534481
&'a FuzzRouter,
535-
Arc<dyn Logger>,
482+
Arc<dyn Logger + MaybeSend + MaybeSync>,
536483
>;
537484

538485
#[inline]
@@ -701,14 +648,14 @@ fn send_hop_payment(
701648
}
702649

703650
#[inline]
704-
pub fn do_test<Out: Output>(data: &[u8], underlying_out: Out, anchors: bool) {
651+
pub fn do_test<Out: Output + MaybeSend + MaybeSync>(data: &[u8], underlying_out: Out, anchors: bool) {
705652
let out = SearchingOutput::new(underlying_out);
706653
let broadcast = Arc::new(TestBroadcaster {});
707654
let router = FuzzRouter {};
708655

709656
macro_rules! make_node {
710657
($node_id: expr, $fee_estimator: expr) => {{
711-
let logger: Arc<dyn Logger> =
658+
let logger: Arc<dyn Logger + MaybeSend + MaybeSync> =
712659
Arc::new(test_logger::TestLogger::new($node_id.to_string(), out.clone()));
713660
let node_secret = SecretKey::from_slice(&[
714661
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
@@ -758,6 +705,7 @@ pub fn do_test<Out: Output>(data: &[u8], underlying_out: Out, anchors: bool) {
758705
),
759706
monitor,
760707
keys_manager,
708+
logger,
761709
)
762710
}};
763711
}
@@ -772,7 +720,7 @@ pub fn do_test<Out: Output>(data: &[u8], underlying_out: Out, anchors: bool) {
772720
keys,
773721
fee_estimator| {
774722
let keys_manager = Arc::clone(keys);
775-
let logger: Arc<dyn Logger> =
723+
let logger: Arc<dyn Logger + MaybeSend + MaybeSync> =
776724
Arc::new(test_logger::TestLogger::new(node_id.to_string(), out.clone()));
777725
let chain_monitor = Arc::new(TestChainMonitor::new(
778726
broadcast.clone(),
@@ -1048,9 +996,9 @@ pub fn do_test<Out: Output>(data: &[u8], underlying_out: Out, anchors: bool) {
1048996
}};
1049997
}
1050998

1051-
let wallet_a = TestWallet::new(SecretKey::from_slice(&[1; 32]).unwrap());
1052-
let wallet_b = TestWallet::new(SecretKey::from_slice(&[2; 32]).unwrap());
1053-
let wallet_c = TestWallet::new(SecretKey::from_slice(&[3; 32]).unwrap());
999+
let wallet_a = TestWalletSource::new(SecretKey::from_slice(&[1; 32]).unwrap());
1000+
let wallet_b = TestWalletSource::new(SecretKey::from_slice(&[2; 32]).unwrap());
1001+
let wallet_c = TestWalletSource::new(SecretKey::from_slice(&[3; 32]).unwrap());
10541002
let wallets = vec![wallet_a, wallet_b, wallet_c];
10551003
let coinbase_tx = bitcoin::Transaction {
10561004
version: bitcoin::transaction::Version::TWO,
@@ -1064,12 +1012,8 @@ pub fn do_test<Out: Output>(data: &[u8], underlying_out: Out, anchors: bool) {
10641012
})
10651013
.collect(),
10661014
};
1067-
let coinbase_txid = coinbase_tx.compute_txid();
10681015
wallets.iter().enumerate().for_each(|(i, w)| {
1069-
w.add_utxo(
1070-
bitcoin::OutPoint { txid: coinbase_txid, vout: i as u32 },
1071-
Amount::from_sat(100_000),
1072-
);
1016+
w.add_utxo(coinbase_tx.clone(), i as u32);
10731017
});
10741018

10751019
let fee_est_a = Arc::new(FuzzEstimator { ret_val: atomic::AtomicU32::new(253) });
@@ -1081,11 +1025,13 @@ pub fn do_test<Out: Output>(data: &[u8], underlying_out: Out, anchors: bool) {
10811025

10821026
// 3 nodes is enough to hit all the possible cases, notably unknown-source-unknown-dest
10831027
// forwarding.
1084-
let (node_a, mut monitor_a, keys_manager_a) = make_node!(0, fee_est_a);
1085-
let (node_b, mut monitor_b, keys_manager_b) = make_node!(1, fee_est_b);
1086-
let (node_c, mut monitor_c, keys_manager_c) = make_node!(2, fee_est_c);
1028+
let (node_a, mut monitor_a, keys_manager_a, logger_a) = make_node!(0, fee_est_a);
1029+
let (node_b, mut monitor_b, keys_manager_b, logger_b) = make_node!(1, fee_est_b);
1030+
let (node_c, mut monitor_c, keys_manager_c, logger_c) = make_node!(2, fee_est_c);
10871031

10881032
let mut nodes = [node_a, node_b, node_c];
1033+
let loggers = [logger_a, logger_b, logger_c];
1034+
let fee_estimators = [Arc::clone(&fee_est_a), Arc::clone(&fee_est_b), Arc::clone(&fee_est_c)];
10891035

10901036
let chan_1_id = make_channel!(nodes[0], nodes[1], keys_manager_b, 0);
10911037
let chan_2_id = make_channel!(nodes[1], nodes[2], keys_manager_c, 1);
@@ -1536,6 +1482,29 @@ pub fn do_test<Out: Output>(data: &[u8], underlying_out: Out, anchors: bool) {
15361482
events::Event::ChannelReady { .. } => {},
15371483
events::Event::HTLCHandlingFailed { .. } => {},
15381484

1485+
events::Event::FundingNeeded {
1486+
channel_id,
1487+
counterparty_node_id,
1488+
funding_template,
1489+
..
1490+
} => {
1491+
let wallet =
1492+
WalletSync::new(&wallets[$node], Arc::clone(&loggers[$node]));
1493+
let feerate_sat_per_kw =
1494+
fee_estimators[$node].ret_val.load(atomic::Ordering::Acquire);
1495+
let feerate = FeeRate::from_sat_per_kwu(feerate_sat_per_kw as u64);
1496+
let contribution =
1497+
funding_template.build_sync(&wallet, feerate).unwrap();
1498+
let locktime = None;
1499+
nodes[$node]
1500+
.funding_contributed(
1501+
&channel_id,
1502+
&counterparty_node_id,
1503+
contribution,
1504+
locktime,
1505+
)
1506+
.unwrap();
1507+
},
15391508
events::Event::FundingTransactionReadyForSigning {
15401509
channel_id,
15411510
counterparty_node_id,
@@ -2240,7 +2209,7 @@ impl<O: Output> SearchingOutput<O> {
22402209
}
22412210
}
22422211

2243-
pub fn chanmon_consistency_test<Out: Output>(data: &[u8], out: Out) {
2212+
pub fn chanmon_consistency_test<Out: Output + MaybeSend + MaybeSync>(data: &[u8], out: Out) {
22442213
do_test(data, out.clone(), false);
22452214
do_test(data, out, true);
22462215
}

0 commit comments

Comments
 (0)