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};
22 use ln::msgs::OptionalField;
23 use ln::script::ShutdownScript;
24 use routing::scoring::FixedPenaltyScorer;
25 use util::enforcing_trait_impls::{EnforcingSigner, EnforcementState};
27 use util::logger::{Logger, Level, Record};
28 use util::ser::{Readable, ReadableArgs, Writer, Writeable};
30 use bitcoin::blockdata::constants::genesis_block;
31 use bitcoin::blockdata::transaction::{Transaction, TxOut};
32 use bitcoin::blockdata::script::{Builder, Script};
33 use bitcoin::blockdata::opcodes;
34 use bitcoin::blockdata::block::BlockHeader;
35 use bitcoin::network::constants::Network;
36 use bitcoin::hash_types::{BlockHash, Txid};
38 use bitcoin::secp256k1::{SecretKey, PublicKey, Secp256k1, Signature};
39 use bitcoin::secp256k1::recovery::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 pub struct TestVecWriter(pub Vec<u8>);
53 impl Writer for TestVecWriter {
54 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
55 self.0.extend_from_slice(buf);
60 pub struct TestFeeEstimator {
61 pub sat_per_kw: Mutex<u32>,
63 impl chaininterface::FeeEstimator for TestFeeEstimator {
64 fn get_est_sat_per_1000_weight(&self, _confirmation_target: ConfirmationTarget) -> u32 {
65 *self.sat_per_kw.lock().unwrap()
69 pub struct OnlyReadsKeysInterface {}
70 impl keysinterface::KeysInterface for OnlyReadsKeysInterface {
71 type Signer = EnforcingSigner;
73 fn get_node_secret(&self, _recipient: Recipient) -> Result<SecretKey, ()> { unreachable!(); }
74 fn get_inbound_payment_key_material(&self) -> KeyMaterial { unreachable!(); }
75 fn get_destination_script(&self) -> Script { unreachable!(); }
76 fn get_shutdown_scriptpubkey(&self) -> ShutdownScript { unreachable!(); }
77 fn get_channel_signer(&self, _inbound: bool, _channel_value_satoshis: u64) -> EnforcingSigner { unreachable!(); }
78 fn get_secure_random_bytes(&self) -> [u8; 32] { [0; 32] }
80 fn read_chan_signer(&self, mut reader: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
81 let dummy_sk = SecretKey::from_slice(&[42; 32]).unwrap();
82 let inner: InMemorySigner = ReadableArgs::read(&mut reader, dummy_sk)?;
83 let state = Arc::new(Mutex::new(EnforcementState::new()));
85 Ok(EnforcingSigner::new_with_revoked(
91 fn sign_invoice(&self, _hrp_bytes: &[u8], _invoice_data: &[u5], _recipient: Recipient) -> Result<RecoverableSignature, ()> { unreachable!(); }
94 pub struct TestChainMonitor<'a> {
95 pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<EnforcingSigner>)>>,
96 pub monitor_updates: Mutex<HashMap<[u8; 32], Vec<channelmonitor::ChannelMonitorUpdate>>>,
97 pub latest_monitor_update_id: Mutex<HashMap<[u8; 32], (OutPoint, u64, MonitorUpdateId)>>,
98 pub chain_monitor: chainmonitor::ChainMonitor<EnforcingSigner, &'a TestChainSource, &'a chaininterface::BroadcasterInterface, &'a TestFeeEstimator, &'a TestLogger, &'a chainmonitor::Persist<EnforcingSigner>>,
99 pub keys_manager: &'a TestKeysInterface,
100 /// If this is set to Some(), the next update_channel call (not watch_channel) must be a
101 /// ChannelForceClosed event for the given channel_id with should_broadcast set to the given
103 pub expect_channel_force_closed: Mutex<Option<([u8; 32], bool)>>,
105 impl<'a> TestChainMonitor<'a> {
106 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 {
108 added_monitors: Mutex::new(Vec::new()),
109 monitor_updates: Mutex::new(HashMap::new()),
110 latest_monitor_update_id: Mutex::new(HashMap::new()),
111 chain_monitor: chainmonitor::ChainMonitor::new(chain_source, broadcaster, logger, fee_estimator, persister),
113 expect_channel_force_closed: Mutex::new(None),
117 impl<'a> chain::Watch<EnforcingSigner> for TestChainMonitor<'a> {
118 fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingSigner>) -> Result<(), chain::ChannelMonitorUpdateErr> {
119 // At every point where we get a monitor update, we should be able to send a useful monitor
120 // to a watchtower and disk...
121 let mut w = TestVecWriter(Vec::new());
122 monitor.write(&mut w).unwrap();
123 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
124 &mut io::Cursor::new(&w.0), self.keys_manager).unwrap().1;
125 assert!(new_monitor == monitor);
126 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
127 (funding_txo, monitor.get_latest_update_id(), MonitorUpdateId::from_new_monitor(&monitor)));
128 self.added_monitors.lock().unwrap().push((funding_txo, monitor));
129 self.chain_monitor.watch_channel(funding_txo, new_monitor)
132 fn update_channel(&self, funding_txo: OutPoint, update: channelmonitor::ChannelMonitorUpdate) -> Result<(), chain::ChannelMonitorUpdateErr> {
133 // Every monitor update should survive roundtrip
134 let mut w = TestVecWriter(Vec::new());
135 update.write(&mut w).unwrap();
136 assert!(channelmonitor::ChannelMonitorUpdate::read(
137 &mut io::Cursor::new(&w.0)).unwrap() == update);
139 self.monitor_updates.lock().unwrap().entry(funding_txo.to_channel_id()).or_insert(Vec::new()).push(update.clone());
141 if let Some(exp) = self.expect_channel_force_closed.lock().unwrap().take() {
142 assert_eq!(funding_txo.to_channel_id(), exp.0);
143 assert_eq!(update.updates.len(), 1);
144 if let channelmonitor::ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
145 assert_eq!(should_broadcast, exp.1);
149 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
150 (funding_txo, update.update_id, MonitorUpdateId::from_monitor_update(&update)));
151 let update_res = self.chain_monitor.update_channel(funding_txo, update);
152 // At every point where we get a monitor update, we should be able to send a useful monitor
153 // to a watchtower and disk...
154 let monitor = self.chain_monitor.get_monitor(funding_txo).unwrap();
156 monitor.write(&mut w).unwrap();
157 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
158 &mut io::Cursor::new(&w.0), self.keys_manager).unwrap().1;
159 assert!(new_monitor == *monitor);
160 self.added_monitors.lock().unwrap().push((funding_txo, new_monitor));
164 fn release_pending_monitor_events(&self) -> Vec<MonitorEvent> {
165 return self.chain_monitor.release_pending_monitor_events();
169 pub struct TestPersister {
170 pub update_ret: Mutex<Result<(), chain::ChannelMonitorUpdateErr>>,
171 /// If this is set to Some(), after the next return, we'll always return this until update_ret
173 pub next_update_ret: Mutex<Option<Result<(), chain::ChannelMonitorUpdateErr>>>,
174 /// When we get an update_persisted_channel call with no ChannelMonitorUpdate, we insert the
175 /// MonitorUpdateId here.
176 pub chain_sync_monitor_persistences: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
177 /// When we get an update_persisted_channel call *with* a ChannelMonitorUpdate, we insert the
178 /// MonitorUpdateId here.
179 pub offchain_monitor_updates: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
182 pub fn new() -> Self {
184 update_ret: Mutex::new(Ok(())),
185 next_update_ret: Mutex::new(None),
186 chain_sync_monitor_persistences: Mutex::new(HashMap::new()),
187 offchain_monitor_updates: Mutex::new(HashMap::new()),
191 pub fn set_update_ret(&self, ret: Result<(), chain::ChannelMonitorUpdateErr>) {
192 *self.update_ret.lock().unwrap() = ret;
195 pub fn set_next_update_ret(&self, next_ret: Option<Result<(), chain::ChannelMonitorUpdateErr>>) {
196 *self.next_update_ret.lock().unwrap() = next_ret;
199 impl<Signer: keysinterface::Sign> chainmonitor::Persist<Signer> for TestPersister {
200 fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor<Signer>, _id: MonitorUpdateId) -> Result<(), chain::ChannelMonitorUpdateErr> {
201 let ret = self.update_ret.lock().unwrap().clone();
202 if let Some(next_ret) = self.next_update_ret.lock().unwrap().take() {
203 *self.update_ret.lock().unwrap() = next_ret;
208 fn update_persisted_channel(&self, funding_txo: OutPoint, update: &Option<channelmonitor::ChannelMonitorUpdate>, _data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId) -> Result<(), chain::ChannelMonitorUpdateErr> {
209 let ret = self.update_ret.lock().unwrap().clone();
210 if let Some(next_ret) = self.next_update_ret.lock().unwrap().take() {
211 *self.update_ret.lock().unwrap() = next_ret;
213 if update.is_none() {
214 self.chain_sync_monitor_persistences.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
216 self.offchain_monitor_updates.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
222 pub struct TestBroadcaster {
223 pub txn_broadcasted: Mutex<Vec<Transaction>>,
224 pub blocks: Arc<Mutex<Vec<(BlockHeader, u32)>>>,
227 impl TestBroadcaster {
228 pub fn new(blocks: Arc<Mutex<Vec<(BlockHeader, u32)>>>) -> TestBroadcaster {
229 TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks }
233 impl chaininterface::BroadcasterInterface for TestBroadcaster {
234 fn broadcast_transaction(&self, tx: &Transaction) {
235 assert!(tx.lock_time < 1_500_000_000);
236 if tx.lock_time > self.blocks.lock().unwrap().len() as u32 + 1 && tx.lock_time < 500_000_000 {
237 for inp in tx.input.iter() {
238 if inp.sequence != 0xffffffff {
239 panic!("We should never broadcast a transaction before its locktime ({})!", tx.lock_time);
243 self.txn_broadcasted.lock().unwrap().push(tx.clone());
247 pub struct TestChannelMessageHandler {
248 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
251 impl TestChannelMessageHandler {
252 pub fn new() -> Self {
253 TestChannelMessageHandler {
254 pending_events: Mutex::new(Vec::new()),
259 impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
260 fn handle_open_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, _msg: &msgs::OpenChannel) {}
261 fn handle_accept_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, _msg: &msgs::AcceptChannel) {}
262 fn handle_funding_created(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingCreated) {}
263 fn handle_funding_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingSigned) {}
264 fn handle_funding_locked(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingLocked) {}
265 fn handle_shutdown(&self, _their_node_id: &PublicKey, _their_features: &InitFeatures, _msg: &msgs::Shutdown) {}
266 fn handle_closing_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::ClosingSigned) {}
267 fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateAddHTLC) {}
268 fn handle_update_fulfill_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFulfillHTLC) {}
269 fn handle_update_fail_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFailHTLC) {}
270 fn handle_update_fail_malformed_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFailMalformedHTLC) {}
271 fn handle_commitment_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::CommitmentSigned) {}
272 fn handle_revoke_and_ack(&self, _their_node_id: &PublicKey, _msg: &msgs::RevokeAndACK) {}
273 fn handle_update_fee(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFee) {}
274 fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {}
275 fn handle_announcement_signatures(&self, _their_node_id: &PublicKey, _msg: &msgs::AnnouncementSignatures) {}
276 fn handle_channel_reestablish(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelReestablish) {}
277 fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
278 fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) {}
279 fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
282 impl events::MessageSendEventsProvider for TestChannelMessageHandler {
283 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
284 let mut pending_events = self.pending_events.lock().unwrap();
285 let mut ret = Vec::new();
286 mem::swap(&mut ret, &mut *pending_events);
291 fn get_dummy_channel_announcement(short_chan_id: u64) -> msgs::ChannelAnnouncement {
292 use bitcoin::secp256k1::ffi::Signature as FFISignature;
293 let secp_ctx = Secp256k1::new();
294 let network = Network::Testnet;
295 let node_1_privkey = SecretKey::from_slice(&[42; 32]).unwrap();
296 let node_2_privkey = SecretKey::from_slice(&[41; 32]).unwrap();
297 let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
298 let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
299 let unsigned_ann = msgs::UnsignedChannelAnnouncement {
300 features: ChannelFeatures::known(),
301 chain_hash: genesis_block(network).header.block_hash(),
302 short_channel_id: short_chan_id,
303 node_id_1: PublicKey::from_secret_key(&secp_ctx, &node_1_privkey),
304 node_id_2: PublicKey::from_secret_key(&secp_ctx, &node_2_privkey),
305 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, &node_1_btckey),
306 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, &node_2_btckey),
307 excess_data: Vec::new(),
311 msgs::ChannelAnnouncement {
312 node_signature_1: Signature::from(FFISignature::new()),
313 node_signature_2: Signature::from(FFISignature::new()),
314 bitcoin_signature_1: Signature::from(FFISignature::new()),
315 bitcoin_signature_2: Signature::from(FFISignature::new()),
316 contents: unsigned_ann,
321 fn get_dummy_channel_update(short_chan_id: u64) -> msgs::ChannelUpdate {
322 use bitcoin::secp256k1::ffi::Signature as FFISignature;
323 let network = Network::Testnet;
324 msgs::ChannelUpdate {
325 signature: Signature::from(unsafe { FFISignature::new() }),
326 contents: msgs::UnsignedChannelUpdate {
327 chain_hash: genesis_block(network).header.block_hash(),
328 short_channel_id: short_chan_id,
331 cltv_expiry_delta: 0,
332 htlc_minimum_msat: 0,
333 htlc_maximum_msat: OptionalField::Absent,
335 fee_proportional_millionths: 0,
341 pub struct TestRoutingMessageHandler {
342 pub chan_upds_recvd: AtomicUsize,
343 pub chan_anns_recvd: AtomicUsize,
344 pub request_full_sync: AtomicBool,
347 impl TestRoutingMessageHandler {
348 pub fn new() -> Self {
349 TestRoutingMessageHandler {
350 chan_upds_recvd: AtomicUsize::new(0),
351 chan_anns_recvd: AtomicUsize::new(0),
352 request_full_sync: AtomicBool::new(false),
356 impl msgs::RoutingMessageHandler for TestRoutingMessageHandler {
357 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, msgs::LightningError> {
358 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
360 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, msgs::LightningError> {
361 self.chan_anns_recvd.fetch_add(1, Ordering::AcqRel);
362 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
364 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, msgs::LightningError> {
365 self.chan_upds_recvd.fetch_add(1, Ordering::AcqRel);
366 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
368 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
369 let mut chan_anns = Vec::new();
370 const TOTAL_UPDS: u64 = 50;
371 let end: u64 = cmp::min(starting_point + batch_amount as u64, TOTAL_UPDS);
372 for i in starting_point..end {
373 let chan_upd_1 = get_dummy_channel_update(i);
374 let chan_upd_2 = get_dummy_channel_update(i);
375 let chan_ann = get_dummy_channel_announcement(i);
377 chan_anns.push((chan_ann, Some(chan_upd_1), Some(chan_upd_2)));
383 fn get_next_node_announcements(&self, _starting_point: Option<&PublicKey>, _batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
387 fn sync_routing_table(&self, _their_node_id: &PublicKey, _init_msg: &msgs::Init) {}
389 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), msgs::LightningError> {
393 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), msgs::LightningError> {
397 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), msgs::LightningError> {
401 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), msgs::LightningError> {
406 impl events::MessageSendEventsProvider for TestRoutingMessageHandler {
407 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
412 pub struct TestLogger {
415 pub lines: Mutex<HashMap<(String, String), usize>>,
419 pub fn new() -> TestLogger {
420 Self::with_id("".to_owned())
422 pub fn with_id(id: String) -> TestLogger {
426 lines: Mutex::new(HashMap::new())
429 pub fn enable(&mut self, level: Level) {
432 pub fn assert_log(&self, module: String, line: String, count: usize) {
433 let log_entries = self.lines.lock().unwrap();
434 assert_eq!(log_entries.get(&(module, line)), Some(&count));
437 /// Search for the number of occurrence of the logged lines which
438 /// 1. belongs to the specified module and
439 /// 2. contains `line` in it.
440 /// And asserts if the number of occurrences is the same with the given `count`
441 pub fn assert_log_contains(&self, module: String, line: String, count: usize) {
442 let log_entries = self.lines.lock().unwrap();
443 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
444 m == &module && l.contains(line.as_str())
445 }).map(|(_, c) | { c }).sum();
449 /// Search for the number of occurrences of logged lines which
450 /// 1. belong to the specified module and
451 /// 2. match the given regex pattern.
452 /// Assert that the number of occurrences equals the given `count`
453 pub fn assert_log_regex(&self, module: String, pattern: regex::Regex, count: usize) {
454 let log_entries = self.lines.lock().unwrap();
455 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
456 m == &module && pattern.is_match(&l)
457 }).map(|(_, c) | { c }).sum();
462 impl Logger for TestLogger {
463 fn log(&self, record: &Record) {
464 *self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1;
465 if record.level >= self.level {
466 #[cfg(feature = "std")]
467 println!("{:<5} {} [{} : {}, {}] {}", record.level.to_string(), self.id, record.module_path, record.file, record.line, record.args);
472 pub struct TestKeysInterface {
473 pub backing: keysinterface::PhantomKeysManager,
474 pub override_session_priv: Mutex<Option<[u8; 32]>>,
475 pub override_channel_id_priv: Mutex<Option<[u8; 32]>>,
476 pub disable_revocation_policy_check: bool,
477 enforcement_states: Mutex<HashMap<[u8;32], Arc<Mutex<EnforcementState>>>>,
478 expectations: Mutex<Option<VecDeque<OnGetShutdownScriptpubkey>>>,
481 impl keysinterface::KeysInterface for TestKeysInterface {
482 type Signer = EnforcingSigner;
484 fn get_node_secret(&self, recipient: Recipient) -> Result<SecretKey, ()> {
485 self.backing.get_node_secret(recipient)
487 fn get_inbound_payment_key_material(&self) -> keysinterface::KeyMaterial {
488 self.backing.get_inbound_payment_key_material()
490 fn get_destination_script(&self) -> Script { self.backing.get_destination_script() }
492 fn get_shutdown_scriptpubkey(&self) -> ShutdownScript {
493 match &mut *self.expectations.lock().unwrap() {
494 None => self.backing.get_shutdown_scriptpubkey(),
495 Some(expectations) => match expectations.pop_front() {
496 None => panic!("Unexpected get_shutdown_scriptpubkey"),
497 Some(expectation) => expectation.returns,
502 fn get_channel_signer(&self, inbound: bool, channel_value_satoshis: u64) -> EnforcingSigner {
503 let keys = self.backing.get_channel_signer(inbound, channel_value_satoshis);
504 let state = self.make_enforcement_state_cell(keys.commitment_seed);
505 EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
508 fn get_secure_random_bytes(&self) -> [u8; 32] {
509 let override_channel_id = self.override_channel_id_priv.lock().unwrap();
510 let override_session_key = self.override_session_priv.lock().unwrap();
511 if override_channel_id.is_some() && override_session_key.is_some() {
512 panic!("We don't know which override key to use!");
514 if let Some(key) = &*override_channel_id {
517 if let Some(key) = &*override_session_key {
520 self.backing.get_secure_random_bytes()
523 fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
524 let mut reader = io::Cursor::new(buffer);
526 let inner: InMemorySigner = ReadableArgs::read(&mut reader, self.get_node_secret(Recipient::Node).unwrap())?;
527 let state = self.make_enforcement_state_cell(inner.commitment_seed);
529 Ok(EnforcingSigner::new_with_revoked(
532 self.disable_revocation_policy_check
536 fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()> {
537 self.backing.sign_invoice(hrp_bytes, invoice_data, recipient)
541 impl TestKeysInterface {
542 pub fn new(seed: &[u8; 32], network: Network) -> Self {
543 let now = Duration::from_secs(genesis_block(network).header.time as u64);
545 backing: keysinterface::PhantomKeysManager::new(seed, now.as_secs(), now.subsec_nanos(), seed),
546 override_session_priv: Mutex::new(None),
547 override_channel_id_priv: Mutex::new(None),
548 disable_revocation_policy_check: false,
549 enforcement_states: Mutex::new(HashMap::new()),
550 expectations: Mutex::new(None),
554 /// Sets an expectation that [`keysinterface::KeysInterface::get_shutdown_scriptpubkey`] is
556 pub fn expect(&self, expectation: OnGetShutdownScriptpubkey) -> &Self {
557 self.expectations.lock().unwrap()
558 .get_or_insert_with(|| VecDeque::new())
559 .push_back(expectation);
563 pub fn derive_channel_keys(&self, channel_value_satoshis: u64, id: &[u8; 32]) -> EnforcingSigner {
564 let keys = self.backing.derive_channel_keys(channel_value_satoshis, id);
565 let state = self.make_enforcement_state_cell(keys.commitment_seed);
566 EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
569 fn make_enforcement_state_cell(&self, commitment_seed: [u8; 32]) -> Arc<Mutex<EnforcementState>> {
570 let mut states = self.enforcement_states.lock().unwrap();
571 if !states.contains_key(&commitment_seed) {
572 let state = EnforcementState::new();
573 states.insert(commitment_seed, Arc::new(Mutex::new(state)));
575 let cell = states.get(&commitment_seed).unwrap();
580 pub(crate) fn panicking() -> bool {
581 #[cfg(feature = "std")]
582 let panicking = ::std::thread::panicking();
583 #[cfg(not(feature = "std"))]
584 let panicking = false;
588 impl Drop for TestKeysInterface {
594 if let Some(expectations) = &*self.expectations.lock().unwrap() {
595 if !expectations.is_empty() {
596 panic!("Unsatisfied expectations: {:?}", expectations);
602 /// An expectation that [`keysinterface::KeysInterface::get_shutdown_scriptpubkey`] was called and
603 /// returns a [`ShutdownScript`].
604 pub struct OnGetShutdownScriptpubkey {
605 /// A shutdown script used to close a channel.
606 pub returns: ShutdownScript,
609 impl core::fmt::Debug for OnGetShutdownScriptpubkey {
610 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
611 f.debug_struct("OnGetShutdownScriptpubkey").finish()
615 pub struct TestChainSource {
616 pub genesis_hash: BlockHash,
617 pub utxo_ret: Mutex<Result<TxOut, chain::AccessError>>,
618 pub watched_txn: Mutex<HashSet<(Txid, Script)>>,
619 pub watched_outputs: Mutex<HashSet<(OutPoint, Script)>>,
620 expectations: Mutex<Option<VecDeque<OnRegisterOutput>>>,
623 impl TestChainSource {
624 pub fn new(network: Network) -> Self {
625 let script_pubkey = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
627 genesis_hash: genesis_block(network).block_hash(),
628 utxo_ret: Mutex::new(Ok(TxOut { value: u64::max_value(), script_pubkey })),
629 watched_txn: Mutex::new(HashSet::new()),
630 watched_outputs: Mutex::new(HashSet::new()),
631 expectations: Mutex::new(None),
635 /// Sets an expectation that [`chain::Filter::register_output`] is called.
636 pub fn expect(&self, expectation: OnRegisterOutput) -> &Self {
637 self.expectations.lock().unwrap()
638 .get_or_insert_with(|| VecDeque::new())
639 .push_back(expectation);
644 impl chain::Access for TestChainSource {
645 fn get_utxo(&self, genesis_hash: &BlockHash, _short_channel_id: u64) -> Result<TxOut, chain::AccessError> {
646 if self.genesis_hash != *genesis_hash {
647 return Err(chain::AccessError::UnknownChain);
650 self.utxo_ret.lock().unwrap().clone()
654 impl chain::Filter for TestChainSource {
655 fn register_tx(&self, txid: &Txid, script_pubkey: &Script) {
656 self.watched_txn.lock().unwrap().insert((*txid, script_pubkey.clone()));
659 fn register_output(&self, output: WatchedOutput) -> Option<(usize, Transaction)> {
660 let dependent_tx = match &mut *self.expectations.lock().unwrap() {
662 Some(expectations) => match expectations.pop_front() {
664 panic!("Unexpected register_output: {:?}",
665 (output.outpoint, output.script_pubkey));
667 Some(expectation) => {
668 assert_eq!(output.outpoint, expectation.outpoint());
669 assert_eq!(&output.script_pubkey, expectation.script_pubkey());
675 self.watched_outputs.lock().unwrap().insert((output.outpoint, output.script_pubkey));
680 impl Drop for TestChainSource {
686 if let Some(expectations) = &*self.expectations.lock().unwrap() {
687 if !expectations.is_empty() {
688 panic!("Unsatisfied expectations: {:?}", expectations);
694 /// An expectation that [`chain::Filter::register_output`] was called with a transaction output and
695 /// returns an optional dependent transaction that spends the output in the same block.
696 pub struct OnRegisterOutput {
697 /// The transaction output to register.
698 pub with: TxOutReference,
700 /// A dependent transaction spending the output along with its position in the block.
701 pub returns: Option<(usize, Transaction)>,
704 /// A transaction output as identified by an index into a transaction's output list.
705 pub struct TxOutReference(pub Transaction, pub usize);
707 impl OnRegisterOutput {
708 fn outpoint(&self) -> OutPoint {
709 let txid = self.with.0.txid();
710 let index = self.with.1 as u16;
711 OutPoint { txid, index }
714 fn script_pubkey(&self) -> &Script {
715 let index = self.with.1;
716 &self.with.0.output[index].script_pubkey
720 impl core::fmt::Debug for OnRegisterOutput {
721 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
722 f.debug_struct("OnRegisterOutput")
723 .field("outpoint", &self.outpoint())
724 .field("script_pubkey", self.script_pubkey())
729 /// A scorer useful in testing, when the passage of time isn't a concern.
730 pub type TestScorer = FixedPenaltyScorer;