1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
11 use chain::WatchedOutput;
12 use chain::chaininterface;
13 use chain::chaininterface::ConfirmationTarget;
14 use chain::chainmonitor;
15 use chain::chainmonitor::MonitorUpdateId;
16 use chain::channelmonitor;
17 use chain::channelmonitor::MonitorEvent;
18 use chain::transaction::OutPoint;
19 use chain::keysinterface;
20 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
22 use ln::script::ShutdownScript;
23 use routing::scoring::FixedPenaltyScorer;
24 use util::enforcing_trait_impls::{EnforcingSigner, EnforcementState};
26 use util::logger::{Logger, Level, Record};
27 use util::ser::{Readable, ReadableArgs, Writer, Writeable};
29 use bitcoin::blockdata::constants::genesis_block;
30 use bitcoin::blockdata::transaction::{Transaction, TxOut};
31 use bitcoin::blockdata::script::{Builder, Script};
32 use bitcoin::blockdata::opcodes;
33 use bitcoin::blockdata::block::Block;
34 use bitcoin::network::constants::Network;
35 use bitcoin::hash_types::{BlockHash, Txid};
37 use bitcoin::secp256k1::{SecretKey, PublicKey, Secp256k1, ecdsa::Signature, Scalar};
38 use bitcoin::secp256k1::ecdh::SharedSecret;
39 use bitcoin::secp256k1::ecdsa::RecoverableSignature;
45 use core::time::Duration;
46 use sync::{Mutex, Arc};
47 use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
49 use bitcoin::bech32::u5;
50 use chain::keysinterface::{InMemorySigner, Recipient, KeyMaterial};
52 #[cfg(feature = "std")]
53 use std::time::{SystemTime, UNIX_EPOCH};
54 use bitcoin::Sequence;
56 pub struct TestVecWriter(pub Vec<u8>);
57 impl Writer for TestVecWriter {
58 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
59 self.0.extend_from_slice(buf);
64 pub struct TestFeeEstimator {
65 pub sat_per_kw: Mutex<u32>,
67 impl chaininterface::FeeEstimator for TestFeeEstimator {
68 fn get_est_sat_per_1000_weight(&self, _confirmation_target: ConfirmationTarget) -> u32 {
69 *self.sat_per_kw.lock().unwrap()
73 pub struct OnlyReadsKeysInterface {}
74 impl keysinterface::KeysInterface for OnlyReadsKeysInterface {
75 type Signer = EnforcingSigner;
77 fn get_node_secret(&self, _recipient: Recipient) -> Result<SecretKey, ()> { unreachable!(); }
78 fn ecdh(&self, _recipient: Recipient, _other_key: &PublicKey, _tweak: Option<&Scalar>) -> Result<SharedSecret, ()> { unreachable!(); }
79 fn get_inbound_payment_key_material(&self) -> KeyMaterial { unreachable!(); }
80 fn get_destination_script(&self) -> Script { unreachable!(); }
81 fn get_shutdown_scriptpubkey(&self) -> ShutdownScript { unreachable!(); }
82 fn get_channel_signer(&self, _inbound: bool, _channel_value_satoshis: u64) -> EnforcingSigner { unreachable!(); }
83 fn get_secure_random_bytes(&self) -> [u8; 32] { [0; 32] }
85 fn read_chan_signer(&self, mut reader: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
86 let dummy_sk = SecretKey::from_slice(&[42; 32]).unwrap();
87 let inner: InMemorySigner = ReadableArgs::read(&mut reader, dummy_sk)?;
88 let state = Arc::new(Mutex::new(EnforcementState::new()));
90 Ok(EnforcingSigner::new_with_revoked(
96 fn sign_invoice(&self, _hrp_bytes: &[u8], _invoice_data: &[u5], _recipient: Recipient) -> Result<RecoverableSignature, ()> { unreachable!(); }
99 pub struct TestChainMonitor<'a> {
100 pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<EnforcingSigner>)>>,
101 pub monitor_updates: Mutex<HashMap<[u8; 32], Vec<channelmonitor::ChannelMonitorUpdate>>>,
102 pub latest_monitor_update_id: Mutex<HashMap<[u8; 32], (OutPoint, u64, MonitorUpdateId)>>,
103 pub chain_monitor: chainmonitor::ChainMonitor<EnforcingSigner, &'a TestChainSource, &'a chaininterface::BroadcasterInterface, &'a TestFeeEstimator, &'a TestLogger, &'a chainmonitor::Persist<EnforcingSigner>>,
104 pub keys_manager: &'a TestKeysInterface,
105 /// If this is set to Some(), the next update_channel call (not watch_channel) must be a
106 /// ChannelForceClosed event for the given channel_id with should_broadcast set to the given
108 pub expect_channel_force_closed: Mutex<Option<([u8; 32], bool)>>,
110 impl<'a> TestChainMonitor<'a> {
111 pub fn new(chain_source: Option<&'a TestChainSource>, broadcaster: &'a chaininterface::BroadcasterInterface, logger: &'a TestLogger, fee_estimator: &'a TestFeeEstimator, persister: &'a chainmonitor::Persist<EnforcingSigner>, keys_manager: &'a TestKeysInterface) -> Self {
113 added_monitors: Mutex::new(Vec::new()),
114 monitor_updates: Mutex::new(HashMap::new()),
115 latest_monitor_update_id: Mutex::new(HashMap::new()),
116 chain_monitor: chainmonitor::ChainMonitor::new(chain_source, broadcaster, logger, fee_estimator, persister),
118 expect_channel_force_closed: Mutex::new(None),
122 pub fn complete_sole_pending_chan_update(&self, channel_id: &[u8; 32]) {
123 let (outpoint, _, latest_update) = self.latest_monitor_update_id.lock().unwrap().get(channel_id).unwrap().clone();
124 self.chain_monitor.channel_monitor_updated(outpoint, latest_update).unwrap();
127 impl<'a> chain::Watch<EnforcingSigner> for TestChainMonitor<'a> {
128 fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingSigner>) -> Result<(), chain::ChannelMonitorUpdateErr> {
129 // At every point where we get a monitor update, we should be able to send a useful monitor
130 // to a watchtower and disk...
131 let mut w = TestVecWriter(Vec::new());
132 monitor.write(&mut w).unwrap();
133 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
134 &mut io::Cursor::new(&w.0), self.keys_manager).unwrap().1;
135 assert!(new_monitor == monitor);
136 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
137 (funding_txo, monitor.get_latest_update_id(), MonitorUpdateId::from_new_monitor(&monitor)));
138 self.added_monitors.lock().unwrap().push((funding_txo, monitor));
139 self.chain_monitor.watch_channel(funding_txo, new_monitor)
142 fn update_channel(&self, funding_txo: OutPoint, update: channelmonitor::ChannelMonitorUpdate) -> Result<(), chain::ChannelMonitorUpdateErr> {
143 // Every monitor update should survive roundtrip
144 let mut w = TestVecWriter(Vec::new());
145 update.write(&mut w).unwrap();
146 assert!(channelmonitor::ChannelMonitorUpdate::read(
147 &mut io::Cursor::new(&w.0)).unwrap() == update);
149 self.monitor_updates.lock().unwrap().entry(funding_txo.to_channel_id()).or_insert(Vec::new()).push(update.clone());
151 if let Some(exp) = self.expect_channel_force_closed.lock().unwrap().take() {
152 assert_eq!(funding_txo.to_channel_id(), exp.0);
153 assert_eq!(update.updates.len(), 1);
154 if let channelmonitor::ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
155 assert_eq!(should_broadcast, exp.1);
159 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
160 (funding_txo, update.update_id, MonitorUpdateId::from_monitor_update(&update)));
161 let update_res = self.chain_monitor.update_channel(funding_txo, update);
162 // At every point where we get a monitor update, we should be able to send a useful monitor
163 // to a watchtower and disk...
164 let monitor = self.chain_monitor.get_monitor(funding_txo).unwrap();
166 monitor.write(&mut w).unwrap();
167 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
168 &mut io::Cursor::new(&w.0), self.keys_manager).unwrap().1;
169 assert!(new_monitor == *monitor);
170 self.added_monitors.lock().unwrap().push((funding_txo, new_monitor));
174 fn release_pending_monitor_events(&self) -> Vec<(OutPoint, Vec<MonitorEvent>, Option<PublicKey>)> {
175 return self.chain_monitor.release_pending_monitor_events();
179 pub struct TestPersister {
180 pub update_ret: Mutex<Result<(), chain::ChannelMonitorUpdateErr>>,
181 /// If this is set to Some(), after the next return, we'll always return this until update_ret
183 pub next_update_ret: Mutex<Option<Result<(), chain::ChannelMonitorUpdateErr>>>,
184 /// When we get an update_persisted_channel call with no ChannelMonitorUpdate, we insert the
185 /// MonitorUpdateId here.
186 pub chain_sync_monitor_persistences: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
187 /// When we get an update_persisted_channel call *with* a ChannelMonitorUpdate, we insert the
188 /// MonitorUpdateId here.
189 pub offchain_monitor_updates: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
192 pub fn new() -> Self {
194 update_ret: Mutex::new(Ok(())),
195 next_update_ret: Mutex::new(None),
196 chain_sync_monitor_persistences: Mutex::new(HashMap::new()),
197 offchain_monitor_updates: Mutex::new(HashMap::new()),
201 pub fn set_update_ret(&self, ret: Result<(), chain::ChannelMonitorUpdateErr>) {
202 *self.update_ret.lock().unwrap() = ret;
205 pub fn set_next_update_ret(&self, next_ret: Option<Result<(), chain::ChannelMonitorUpdateErr>>) {
206 *self.next_update_ret.lock().unwrap() = next_ret;
209 impl<Signer: keysinterface::Sign> chainmonitor::Persist<Signer> for TestPersister {
210 fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor<Signer>, _id: MonitorUpdateId) -> Result<(), chain::ChannelMonitorUpdateErr> {
211 let ret = self.update_ret.lock().unwrap().clone();
212 if let Some(next_ret) = self.next_update_ret.lock().unwrap().take() {
213 *self.update_ret.lock().unwrap() = next_ret;
218 fn update_persisted_channel(&self, funding_txo: OutPoint, update: &Option<channelmonitor::ChannelMonitorUpdate>, _data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId) -> Result<(), chain::ChannelMonitorUpdateErr> {
219 let ret = self.update_ret.lock().unwrap().clone();
220 if let Some(next_ret) = self.next_update_ret.lock().unwrap().take() {
221 *self.update_ret.lock().unwrap() = next_ret;
223 if update.is_none() {
224 self.chain_sync_monitor_persistences.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
226 self.offchain_monitor_updates.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
232 pub struct TestBroadcaster {
233 pub txn_broadcasted: Mutex<Vec<Transaction>>,
234 pub blocks: Arc<Mutex<Vec<(Block, u32)>>>,
237 impl TestBroadcaster {
238 pub fn new(blocks: Arc<Mutex<Vec<(Block, u32)>>>) -> TestBroadcaster {
239 TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks }
243 impl chaininterface::BroadcasterInterface for TestBroadcaster {
244 fn broadcast_transaction(&self, tx: &Transaction) {
245 let lock_time = tx.lock_time.0;
246 assert!(lock_time < 1_500_000_000);
247 if lock_time > self.blocks.lock().unwrap().len() as u32 + 1 && lock_time < 500_000_000 {
248 for inp in tx.input.iter() {
249 if inp.sequence != Sequence::MAX {
250 panic!("We should never broadcast a transaction before its locktime ({})!", tx.lock_time);
254 self.txn_broadcasted.lock().unwrap().push(tx.clone());
258 pub struct TestChannelMessageHandler {
259 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
260 expected_recv_msgs: Mutex<Option<Vec<wire::Message<()>>>>,
263 impl TestChannelMessageHandler {
264 pub fn new() -> Self {
265 TestChannelMessageHandler {
266 pending_events: Mutex::new(Vec::new()),
267 expected_recv_msgs: Mutex::new(None),
272 pub(crate) fn expect_receive_msg(&self, ev: wire::Message<()>) {
273 let mut expected_msgs = self.expected_recv_msgs.lock().unwrap();
274 if expected_msgs.is_none() { *expected_msgs = Some(Vec::new()); }
275 expected_msgs.as_mut().unwrap().push(ev);
278 fn received_msg(&self, _ev: wire::Message<()>) {
279 let mut msgs = self.expected_recv_msgs.lock().unwrap();
280 if msgs.is_none() { return; }
281 assert!(!msgs.as_ref().unwrap().is_empty(), "Received message when we weren't expecting one");
283 assert_eq!(msgs.as_ref().unwrap()[0], _ev);
284 msgs.as_mut().unwrap().remove(0);
288 impl Drop for TestChannelMessageHandler {
290 #[cfg(feature = "std")]
292 let l = self.expected_recv_msgs.lock().unwrap();
293 if !std::thread::panicking() {
294 assert!(l.is_none() || l.as_ref().unwrap().is_empty());
300 impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
301 fn handle_open_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::OpenChannel) {
302 self.received_msg(wire::Message::OpenChannel(msg.clone()));
304 fn handle_accept_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::AcceptChannel) {
305 self.received_msg(wire::Message::AcceptChannel(msg.clone()));
307 fn handle_funding_created(&self, _their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
308 self.received_msg(wire::Message::FundingCreated(msg.clone()));
310 fn handle_funding_signed(&self, _their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
311 self.received_msg(wire::Message::FundingSigned(msg.clone()));
313 fn handle_channel_ready(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
314 self.received_msg(wire::Message::ChannelReady(msg.clone()));
316 fn handle_shutdown(&self, _their_node_id: &PublicKey, _their_features: &InitFeatures, msg: &msgs::Shutdown) {
317 self.received_msg(wire::Message::Shutdown(msg.clone()));
319 fn handle_closing_signed(&self, _their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
320 self.received_msg(wire::Message::ClosingSigned(msg.clone()));
322 fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
323 self.received_msg(wire::Message::UpdateAddHTLC(msg.clone()));
325 fn handle_update_fulfill_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
326 self.received_msg(wire::Message::UpdateFulfillHTLC(msg.clone()));
328 fn handle_update_fail_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
329 self.received_msg(wire::Message::UpdateFailHTLC(msg.clone()));
331 fn handle_update_fail_malformed_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
332 self.received_msg(wire::Message::UpdateFailMalformedHTLC(msg.clone()));
334 fn handle_commitment_signed(&self, _their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
335 self.received_msg(wire::Message::CommitmentSigned(msg.clone()));
337 fn handle_revoke_and_ack(&self, _their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
338 self.received_msg(wire::Message::RevokeAndACK(msg.clone()));
340 fn handle_update_fee(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
341 self.received_msg(wire::Message::UpdateFee(msg.clone()));
343 fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {
344 // Don't call `received_msg` here as `TestRoutingMessageHandler` generates these sometimes
346 fn handle_announcement_signatures(&self, _their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
347 self.received_msg(wire::Message::AnnouncementSignatures(msg.clone()));
349 fn handle_channel_reestablish(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
350 self.received_msg(wire::Message::ChannelReestablish(msg.clone()));
352 fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
353 fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) -> Result<(), ()> {
354 // Don't bother with `received_msg` for Init as its auto-generated and we don't want to
355 // bother re-generating the expected Init message in all tests.
358 fn handle_error(&self, _their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
359 self.received_msg(wire::Message::Error(msg.clone()));
361 fn provided_node_features(&self) -> NodeFeatures {
362 NodeFeatures::known_channel_features()
364 fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
365 InitFeatures::known_channel_features()
369 impl events::MessageSendEventsProvider for TestChannelMessageHandler {
370 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
371 let mut pending_events = self.pending_events.lock().unwrap();
372 let mut ret = Vec::new();
373 mem::swap(&mut ret, &mut *pending_events);
378 fn get_dummy_channel_announcement(short_chan_id: u64) -> msgs::ChannelAnnouncement {
379 use bitcoin::secp256k1::ffi::Signature as FFISignature;
380 let secp_ctx = Secp256k1::new();
381 let network = Network::Testnet;
382 let node_1_privkey = SecretKey::from_slice(&[42; 32]).unwrap();
383 let node_2_privkey = SecretKey::from_slice(&[41; 32]).unwrap();
384 let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
385 let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
386 let unsigned_ann = msgs::UnsignedChannelAnnouncement {
387 features: ChannelFeatures::known(),
388 chain_hash: genesis_block(network).header.block_hash(),
389 short_channel_id: short_chan_id,
390 node_id_1: PublicKey::from_secret_key(&secp_ctx, &node_1_privkey),
391 node_id_2: PublicKey::from_secret_key(&secp_ctx, &node_2_privkey),
392 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, &node_1_btckey),
393 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, &node_2_btckey),
394 excess_data: Vec::new(),
398 msgs::ChannelAnnouncement {
399 node_signature_1: Signature::from(FFISignature::new()),
400 node_signature_2: Signature::from(FFISignature::new()),
401 bitcoin_signature_1: Signature::from(FFISignature::new()),
402 bitcoin_signature_2: Signature::from(FFISignature::new()),
403 contents: unsigned_ann,
408 fn get_dummy_channel_update(short_chan_id: u64) -> msgs::ChannelUpdate {
409 use bitcoin::secp256k1::ffi::Signature as FFISignature;
410 let network = Network::Testnet;
411 msgs::ChannelUpdate {
412 signature: Signature::from(unsafe { FFISignature::new() }),
413 contents: msgs::UnsignedChannelUpdate {
414 chain_hash: genesis_block(network).header.block_hash(),
415 short_channel_id: short_chan_id,
418 cltv_expiry_delta: 0,
419 htlc_minimum_msat: 0,
420 htlc_maximum_msat: msgs::MAX_VALUE_MSAT,
422 fee_proportional_millionths: 0,
428 pub struct TestRoutingMessageHandler {
429 pub chan_upds_recvd: AtomicUsize,
430 pub chan_anns_recvd: AtomicUsize,
431 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
432 pub request_full_sync: AtomicBool,
435 impl TestRoutingMessageHandler {
436 pub fn new() -> Self {
437 TestRoutingMessageHandler {
438 chan_upds_recvd: AtomicUsize::new(0),
439 chan_anns_recvd: AtomicUsize::new(0),
440 pending_events: Mutex::new(vec![]),
441 request_full_sync: AtomicBool::new(false),
445 impl msgs::RoutingMessageHandler for TestRoutingMessageHandler {
446 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, msgs::LightningError> {
447 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
449 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, msgs::LightningError> {
450 self.chan_anns_recvd.fetch_add(1, Ordering::AcqRel);
451 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
453 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, msgs::LightningError> {
454 self.chan_upds_recvd.fetch_add(1, Ordering::AcqRel);
455 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
457 fn get_next_channel_announcement(&self, starting_point: u64) -> Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
458 let chan_upd_1 = get_dummy_channel_update(starting_point);
459 let chan_upd_2 = get_dummy_channel_update(starting_point);
460 let chan_ann = get_dummy_channel_announcement(starting_point);
462 Some((chan_ann, Some(chan_upd_1), Some(chan_upd_2)))
465 fn get_next_node_announcement(&self, _starting_point: Option<&PublicKey>) -> Option<msgs::NodeAnnouncement> {
469 fn peer_connected(&self, their_node_id: &PublicKey, init_msg: &msgs::Init) -> Result<(), ()> {
470 if !init_msg.features.supports_gossip_queries() {
474 #[allow(unused_mut, unused_assignments)]
475 let mut gossip_start_time = 0;
476 #[cfg(feature = "std")]
478 gossip_start_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
479 if self.request_full_sync.load(Ordering::Acquire) {
480 gossip_start_time -= 60 * 60 * 24 * 7 * 2; // 2 weeks ago
482 gossip_start_time -= 60 * 60; // an hour ago
486 let mut pending_events = self.pending_events.lock().unwrap();
487 pending_events.push(events::MessageSendEvent::SendGossipTimestampFilter {
488 node_id: their_node_id.clone(),
489 msg: msgs::GossipTimestampFilter {
490 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
491 first_timestamp: gossip_start_time as u32,
492 timestamp_range: u32::max_value(),
498 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), msgs::LightningError> {
502 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), msgs::LightningError> {
506 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), msgs::LightningError> {
510 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), msgs::LightningError> {
514 fn provided_node_features(&self) -> NodeFeatures {
515 let mut features = NodeFeatures::empty();
516 features.set_gossip_queries_optional();
520 fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
521 let mut features = InitFeatures::empty();
522 features.set_gossip_queries_optional();
527 impl events::MessageSendEventsProvider for TestRoutingMessageHandler {
528 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
529 let mut ret = Vec::new();
530 let mut pending_events = self.pending_events.lock().unwrap();
531 core::mem::swap(&mut ret, &mut pending_events);
536 pub struct TestLogger {
538 pub(crate) id: String,
539 pub lines: Mutex<HashMap<(String, String), usize>>,
543 pub fn new() -> TestLogger {
544 Self::with_id("".to_owned())
546 pub fn with_id(id: String) -> TestLogger {
550 lines: Mutex::new(HashMap::new())
553 pub fn enable(&mut self, level: Level) {
556 pub fn assert_log(&self, module: String, line: String, count: usize) {
557 let log_entries = self.lines.lock().unwrap();
558 assert_eq!(log_entries.get(&(module, line)), Some(&count));
561 /// Search for the number of occurrence of the logged lines which
562 /// 1. belongs to the specified module and
563 /// 2. contains `line` in it.
564 /// And asserts if the number of occurrences is the same with the given `count`
565 pub fn assert_log_contains(&self, module: String, line: String, count: usize) {
566 let log_entries = self.lines.lock().unwrap();
567 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
568 m == &module && l.contains(line.as_str())
569 }).map(|(_, c) | { c }).sum();
573 /// Search for the number of occurrences of logged lines which
574 /// 1. belong to the specified module and
575 /// 2. match the given regex pattern.
576 /// Assert that the number of occurrences equals the given `count`
577 pub fn assert_log_regex(&self, module: String, pattern: regex::Regex, count: usize) {
578 let log_entries = self.lines.lock().unwrap();
579 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
580 m == &module && pattern.is_match(&l)
581 }).map(|(_, c) | { c }).sum();
586 impl Logger for TestLogger {
587 fn log(&self, record: &Record) {
588 *self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1;
589 if record.level >= self.level {
590 #[cfg(feature = "std")]
591 println!("{:<5} {} [{} : {}, {}] {}", record.level.to_string(), self.id, record.module_path, record.file, record.line, record.args);
596 pub struct TestKeysInterface {
597 pub backing: keysinterface::PhantomKeysManager,
598 pub override_random_bytes: Mutex<Option<[u8; 32]>>,
599 pub disable_revocation_policy_check: bool,
600 enforcement_states: Mutex<HashMap<[u8;32], Arc<Mutex<EnforcementState>>>>,
601 expectations: Mutex<Option<VecDeque<OnGetShutdownScriptpubkey>>>,
604 impl keysinterface::KeysInterface for TestKeysInterface {
605 type Signer = EnforcingSigner;
607 fn get_node_secret(&self, recipient: Recipient) -> Result<SecretKey, ()> {
608 self.backing.get_node_secret(recipient)
610 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()> {
611 self.backing.ecdh(recipient, other_key, tweak)
613 fn get_inbound_payment_key_material(&self) -> keysinterface::KeyMaterial {
614 self.backing.get_inbound_payment_key_material()
616 fn get_destination_script(&self) -> Script { self.backing.get_destination_script() }
618 fn get_shutdown_scriptpubkey(&self) -> ShutdownScript {
619 match &mut *self.expectations.lock().unwrap() {
620 None => self.backing.get_shutdown_scriptpubkey(),
621 Some(expectations) => match expectations.pop_front() {
622 None => panic!("Unexpected get_shutdown_scriptpubkey"),
623 Some(expectation) => expectation.returns,
628 fn get_channel_signer(&self, inbound: bool, channel_value_satoshis: u64) -> EnforcingSigner {
629 let keys = self.backing.get_channel_signer(inbound, channel_value_satoshis);
630 let state = self.make_enforcement_state_cell(keys.commitment_seed);
631 EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
634 fn get_secure_random_bytes(&self) -> [u8; 32] {
635 let override_random_bytes = self.override_random_bytes.lock().unwrap();
636 if let Some(bytes) = &*override_random_bytes {
639 self.backing.get_secure_random_bytes()
642 fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
643 let mut reader = io::Cursor::new(buffer);
645 let inner: InMemorySigner = ReadableArgs::read(&mut reader, self.get_node_secret(Recipient::Node).unwrap())?;
646 let state = self.make_enforcement_state_cell(inner.commitment_seed);
648 Ok(EnforcingSigner::new_with_revoked(
651 self.disable_revocation_policy_check
655 fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()> {
656 self.backing.sign_invoice(hrp_bytes, invoice_data, recipient)
660 impl TestKeysInterface {
661 pub fn new(seed: &[u8; 32], network: Network) -> Self {
662 let now = Duration::from_secs(genesis_block(network).header.time as u64);
664 backing: keysinterface::PhantomKeysManager::new(seed, now.as_secs(), now.subsec_nanos(), seed),
665 override_random_bytes: Mutex::new(None),
666 disable_revocation_policy_check: false,
667 enforcement_states: Mutex::new(HashMap::new()),
668 expectations: Mutex::new(None),
672 /// Sets an expectation that [`keysinterface::KeysInterface::get_shutdown_scriptpubkey`] is
674 pub fn expect(&self, expectation: OnGetShutdownScriptpubkey) -> &Self {
675 self.expectations.lock().unwrap()
676 .get_or_insert_with(|| VecDeque::new())
677 .push_back(expectation);
681 pub fn derive_channel_keys(&self, channel_value_satoshis: u64, id: &[u8; 32]) -> EnforcingSigner {
682 let keys = self.backing.derive_channel_keys(channel_value_satoshis, id);
683 let state = self.make_enforcement_state_cell(keys.commitment_seed);
684 EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
687 fn make_enforcement_state_cell(&self, commitment_seed: [u8; 32]) -> Arc<Mutex<EnforcementState>> {
688 let mut states = self.enforcement_states.lock().unwrap();
689 if !states.contains_key(&commitment_seed) {
690 let state = EnforcementState::new();
691 states.insert(commitment_seed, Arc::new(Mutex::new(state)));
693 let cell = states.get(&commitment_seed).unwrap();
698 pub(crate) fn panicking() -> bool {
699 #[cfg(feature = "std")]
700 let panicking = ::std::thread::panicking();
701 #[cfg(not(feature = "std"))]
702 let panicking = false;
706 impl Drop for TestKeysInterface {
712 if let Some(expectations) = &*self.expectations.lock().unwrap() {
713 if !expectations.is_empty() {
714 panic!("Unsatisfied expectations: {:?}", expectations);
720 /// An expectation that [`keysinterface::KeysInterface::get_shutdown_scriptpubkey`] was called and
721 /// returns a [`ShutdownScript`].
722 pub struct OnGetShutdownScriptpubkey {
723 /// A shutdown script used to close a channel.
724 pub returns: ShutdownScript,
727 impl core::fmt::Debug for OnGetShutdownScriptpubkey {
728 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
729 f.debug_struct("OnGetShutdownScriptpubkey").finish()
733 pub struct TestChainSource {
734 pub genesis_hash: BlockHash,
735 pub utxo_ret: Mutex<Result<TxOut, chain::AccessError>>,
736 pub watched_txn: Mutex<HashSet<(Txid, Script)>>,
737 pub watched_outputs: Mutex<HashSet<(OutPoint, Script)>>,
740 impl TestChainSource {
741 pub fn new(network: Network) -> Self {
742 let script_pubkey = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
744 genesis_hash: genesis_block(network).block_hash(),
745 utxo_ret: Mutex::new(Ok(TxOut { value: u64::max_value(), script_pubkey })),
746 watched_txn: Mutex::new(HashSet::new()),
747 watched_outputs: Mutex::new(HashSet::new()),
752 impl chain::Access for TestChainSource {
753 fn get_utxo(&self, genesis_hash: &BlockHash, _short_channel_id: u64) -> Result<TxOut, chain::AccessError> {
754 if self.genesis_hash != *genesis_hash {
755 return Err(chain::AccessError::UnknownChain);
758 self.utxo_ret.lock().unwrap().clone()
762 impl chain::Filter for TestChainSource {
763 fn register_tx(&self, txid: &Txid, script_pubkey: &Script) {
764 self.watched_txn.lock().unwrap().insert((*txid, script_pubkey.clone()));
767 fn register_output(&self, output: WatchedOutput) {
768 self.watched_outputs.lock().unwrap().insert((output.outpoint, output.script_pubkey));
772 impl Drop for TestChainSource {
780 /// A scorer useful in testing, when the passage of time isn't a concern.
781 pub type TestScorer = FixedPenaltyScorer;