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::channelmonitor;
16 use chain::channelmonitor::MonitorEvent;
17 use chain::transaction::OutPoint;
18 use chain::keysinterface;
19 use ln::features::{ChannelFeatures, InitFeatures};
21 use ln::msgs::OptionalField;
22 use util::enforcing_trait_impls::{EnforcingSigner, INITIAL_REVOKED_COMMITMENT_NUMBER};
24 use util::logger::{Logger, Level, Record};
25 use util::ser::{Readable, ReadableArgs, Writer, Writeable};
27 use bitcoin::blockdata::constants::genesis_block;
28 use bitcoin::blockdata::transaction::{Transaction, TxOut};
29 use bitcoin::blockdata::script::{Builder, Script};
30 use bitcoin::blockdata::opcodes;
31 use bitcoin::blockdata::block::BlockHeader;
32 use bitcoin::network::constants::Network;
33 use bitcoin::hash_types::{BlockHash, Txid};
35 use bitcoin::secp256k1::{SecretKey, PublicKey, Secp256k1, Signature};
36 use bitcoin::secp256k1::recovery::RecoverableSignature;
41 use core::time::Duration;
42 use std::sync::{Mutex, Arc};
43 use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
45 use chain::keysinterface::InMemorySigner;
47 pub struct TestVecWriter(pub Vec<u8>);
48 impl Writer for TestVecWriter {
49 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
50 self.0.extend_from_slice(buf);
53 fn size_hint(&mut self, size: usize) {
54 self.0.reserve_exact(size);
58 pub struct TestFeeEstimator {
61 impl chaininterface::FeeEstimator for TestFeeEstimator {
62 fn get_est_sat_per_1000_weight(&self, _confirmation_target: ConfirmationTarget) -> u32 {
67 pub struct OnlyReadsKeysInterface {}
68 impl keysinterface::KeysInterface for OnlyReadsKeysInterface {
69 type Signer = EnforcingSigner;
71 fn get_node_secret(&self) -> SecretKey { unreachable!(); }
72 fn get_destination_script(&self) -> Script { unreachable!(); }
73 fn get_shutdown_pubkey(&self) -> PublicKey { unreachable!(); }
74 fn get_channel_signer(&self, _inbound: bool, _channel_value_satoshis: u64) -> EnforcingSigner { unreachable!(); }
75 fn get_secure_random_bytes(&self) -> [u8; 32] { [0; 32] }
77 fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
78 EnforcingSigner::read(&mut std::io::Cursor::new(reader))
80 fn sign_invoice(&self, _invoice_preimage: Vec<u8>) -> Result<RecoverableSignature, ()> { unreachable!(); }
83 pub struct TestChainMonitor<'a> {
84 pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<EnforcingSigner>)>>,
85 pub latest_monitor_update_id: Mutex<HashMap<[u8; 32], (OutPoint, u64)>>,
86 pub chain_monitor: chainmonitor::ChainMonitor<EnforcingSigner, &'a TestChainSource, &'a chaininterface::BroadcasterInterface, &'a TestFeeEstimator, &'a TestLogger, &'a channelmonitor::Persist<EnforcingSigner>>,
87 pub keys_manager: &'a TestKeysInterface,
88 pub update_ret: Mutex<Option<Result<(), channelmonitor::ChannelMonitorUpdateErr>>>,
89 /// If this is set to Some(), after the next return, we'll always return this until update_ret
91 pub next_update_ret: Mutex<Option<Result<(), channelmonitor::ChannelMonitorUpdateErr>>>,
92 /// If this is set to Some(), the next update_channel call (not watch_channel) must be a
93 /// ChannelForceClosed event for the given channel_id with should_broadcast set to the given
95 pub expect_channel_force_closed: Mutex<Option<([u8; 32], bool)>>,
97 impl<'a> TestChainMonitor<'a> {
98 pub fn new(chain_source: Option<&'a TestChainSource>, broadcaster: &'a chaininterface::BroadcasterInterface, logger: &'a TestLogger, fee_estimator: &'a TestFeeEstimator, persister: &'a channelmonitor::Persist<EnforcingSigner>, keys_manager: &'a TestKeysInterface) -> Self {
100 added_monitors: Mutex::new(Vec::new()),
101 latest_monitor_update_id: Mutex::new(HashMap::new()),
102 chain_monitor: chainmonitor::ChainMonitor::new(chain_source, broadcaster, logger, fee_estimator, persister),
104 update_ret: Mutex::new(None),
105 next_update_ret: Mutex::new(None),
106 expect_channel_force_closed: Mutex::new(None),
110 impl<'a> chain::Watch<EnforcingSigner> for TestChainMonitor<'a> {
111 fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingSigner>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
112 // At every point where we get a monitor update, we should be able to send a useful monitor
113 // to a watchtower and disk...
114 let mut w = TestVecWriter(Vec::new());
115 monitor.write(&mut w).unwrap();
116 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
117 &mut ::std::io::Cursor::new(&w.0), self.keys_manager).unwrap().1;
118 assert!(new_monitor == monitor);
119 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(), (funding_txo, monitor.get_latest_update_id()));
120 self.added_monitors.lock().unwrap().push((funding_txo, monitor));
121 let watch_res = self.chain_monitor.watch_channel(funding_txo, new_monitor);
123 let ret = self.update_ret.lock().unwrap().clone();
124 if let Some(next_ret) = self.next_update_ret.lock().unwrap().take() {
125 *self.update_ret.lock().unwrap() = Some(next_ret);
128 assert!(watch_res.is_ok());
134 fn update_channel(&self, funding_txo: OutPoint, update: channelmonitor::ChannelMonitorUpdate) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
135 // Every monitor update should survive roundtrip
136 let mut w = TestVecWriter(Vec::new());
137 update.write(&mut w).unwrap();
138 assert!(channelmonitor::ChannelMonitorUpdate::read(
139 &mut ::std::io::Cursor::new(&w.0)).unwrap() == update);
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(), (funding_txo, update.update_id));
150 let update_res = self.chain_monitor.update_channel(funding_txo, update);
151 // At every point where we get a monitor update, we should be able to send a useful monitor
152 // to a watchtower and disk...
153 let monitors = self.chain_monitor.monitors.read().unwrap();
154 let monitor = monitors.get(&funding_txo).unwrap();
156 monitor.write(&mut w).unwrap();
157 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
158 &mut ::std::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));
162 let ret = self.update_ret.lock().unwrap().clone();
163 if let Some(next_ret) = self.next_update_ret.lock().unwrap().take() {
164 *self.update_ret.lock().unwrap() = Some(next_ret);
167 assert!(update_res.is_ok());
173 fn release_pending_monitor_events(&self) -> Vec<MonitorEvent> {
174 return self.chain_monitor.release_pending_monitor_events();
178 pub struct TestPersister {
179 pub update_ret: Mutex<Result<(), channelmonitor::ChannelMonitorUpdateErr>>
182 pub fn new() -> Self {
184 update_ret: Mutex::new(Ok(()))
188 pub fn set_update_ret(&self, ret: Result<(), channelmonitor::ChannelMonitorUpdateErr>) {
189 *self.update_ret.lock().unwrap() = ret;
192 impl<Signer: keysinterface::Sign> channelmonitor::Persist<Signer> for TestPersister {
193 fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor<Signer>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
194 self.update_ret.lock().unwrap().clone()
197 fn update_persisted_channel(&self, _funding_txo: OutPoint, _update: &channelmonitor::ChannelMonitorUpdate, _data: &channelmonitor::ChannelMonitor<Signer>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
198 self.update_ret.lock().unwrap().clone()
202 pub struct TestBroadcaster {
203 pub txn_broadcasted: Mutex<Vec<Transaction>>,
204 pub blocks: Arc<Mutex<Vec<(BlockHeader, u32)>>>,
206 impl chaininterface::BroadcasterInterface for TestBroadcaster {
207 fn broadcast_transaction(&self, tx: &Transaction) {
208 assert!(tx.lock_time < 1_500_000_000);
209 if tx.lock_time > self.blocks.lock().unwrap().len() as u32 + 1 && tx.lock_time < 500_000_000 {
210 for inp in tx.input.iter() {
211 if inp.sequence != 0xffffffff {
212 panic!("We should never broadcast a transaction before its locktime ({})!", tx.lock_time);
216 self.txn_broadcasted.lock().unwrap().push(tx.clone());
220 pub struct TestChannelMessageHandler {
221 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
224 impl TestChannelMessageHandler {
225 pub fn new() -> Self {
226 TestChannelMessageHandler {
227 pending_events: Mutex::new(Vec::new()),
232 impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
233 fn handle_open_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, _msg: &msgs::OpenChannel) {}
234 fn handle_accept_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, _msg: &msgs::AcceptChannel) {}
235 fn handle_funding_created(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingCreated) {}
236 fn handle_funding_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingSigned) {}
237 fn handle_funding_locked(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingLocked) {}
238 fn handle_shutdown(&self, _their_node_id: &PublicKey, _their_features: &InitFeatures, _msg: &msgs::Shutdown) {}
239 fn handle_closing_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::ClosingSigned) {}
240 fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateAddHTLC) {}
241 fn handle_update_fulfill_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFulfillHTLC) {}
242 fn handle_update_fail_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFailHTLC) {}
243 fn handle_update_fail_malformed_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFailMalformedHTLC) {}
244 fn handle_commitment_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::CommitmentSigned) {}
245 fn handle_revoke_and_ack(&self, _their_node_id: &PublicKey, _msg: &msgs::RevokeAndACK) {}
246 fn handle_update_fee(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFee) {}
247 fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {}
248 fn handle_announcement_signatures(&self, _their_node_id: &PublicKey, _msg: &msgs::AnnouncementSignatures) {}
249 fn handle_channel_reestablish(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelReestablish) {}
250 fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
251 fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) {}
252 fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
255 impl events::MessageSendEventsProvider for TestChannelMessageHandler {
256 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
257 let mut pending_events = self.pending_events.lock().unwrap();
258 let mut ret = Vec::new();
259 mem::swap(&mut ret, &mut *pending_events);
264 fn get_dummy_channel_announcement(short_chan_id: u64) -> msgs::ChannelAnnouncement {
265 use bitcoin::secp256k1::ffi::Signature as FFISignature;
266 let secp_ctx = Secp256k1::new();
267 let network = Network::Testnet;
268 let node_1_privkey = SecretKey::from_slice(&[42; 32]).unwrap();
269 let node_2_privkey = SecretKey::from_slice(&[41; 32]).unwrap();
270 let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
271 let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
272 let unsigned_ann = msgs::UnsignedChannelAnnouncement {
273 features: ChannelFeatures::known(),
274 chain_hash: genesis_block(network).header.block_hash(),
275 short_channel_id: short_chan_id,
276 node_id_1: PublicKey::from_secret_key(&secp_ctx, &node_1_privkey),
277 node_id_2: PublicKey::from_secret_key(&secp_ctx, &node_2_privkey),
278 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, &node_1_btckey),
279 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, &node_2_btckey),
280 excess_data: Vec::new(),
284 msgs::ChannelAnnouncement {
285 node_signature_1: Signature::from(FFISignature::new()),
286 node_signature_2: Signature::from(FFISignature::new()),
287 bitcoin_signature_1: Signature::from(FFISignature::new()),
288 bitcoin_signature_2: Signature::from(FFISignature::new()),
289 contents: unsigned_ann,
294 fn get_dummy_channel_update(short_chan_id: u64) -> msgs::ChannelUpdate {
295 use bitcoin::secp256k1::ffi::Signature as FFISignature;
296 let network = Network::Testnet;
297 msgs::ChannelUpdate {
298 signature: Signature::from(unsafe { FFISignature::new() }),
299 contents: msgs::UnsignedChannelUpdate {
300 chain_hash: genesis_block(network).header.block_hash(),
301 short_channel_id: short_chan_id,
304 cltv_expiry_delta: 0,
305 htlc_minimum_msat: 0,
306 htlc_maximum_msat: OptionalField::Absent,
308 fee_proportional_millionths: 0,
314 pub struct TestRoutingMessageHandler {
315 pub chan_upds_recvd: AtomicUsize,
316 pub chan_anns_recvd: AtomicUsize,
317 pub chan_anns_sent: AtomicUsize,
318 pub request_full_sync: AtomicBool,
321 impl TestRoutingMessageHandler {
322 pub fn new() -> Self {
323 TestRoutingMessageHandler {
324 chan_upds_recvd: AtomicUsize::new(0),
325 chan_anns_recvd: AtomicUsize::new(0),
326 chan_anns_sent: AtomicUsize::new(0),
327 request_full_sync: AtomicBool::new(false),
331 impl msgs::RoutingMessageHandler for TestRoutingMessageHandler {
332 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, msgs::LightningError> {
333 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
335 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, msgs::LightningError> {
336 self.chan_anns_recvd.fetch_add(1, Ordering::AcqRel);
337 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
339 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, msgs::LightningError> {
340 self.chan_upds_recvd.fetch_add(1, Ordering::AcqRel);
341 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
343 fn handle_htlc_fail_channel_update(&self, _update: &msgs::HTLCFailChannelUpdate) {}
344 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
345 let mut chan_anns = Vec::new();
346 const TOTAL_UPDS: u64 = 100;
347 let end: u64 = cmp::min(starting_point + batch_amount as u64, TOTAL_UPDS - self.chan_anns_sent.load(Ordering::Acquire) as u64);
348 for i in starting_point..end {
349 let chan_upd_1 = get_dummy_channel_update(i);
350 let chan_upd_2 = get_dummy_channel_update(i);
351 let chan_ann = get_dummy_channel_announcement(i);
353 chan_anns.push((chan_ann, Some(chan_upd_1), Some(chan_upd_2)));
356 self.chan_anns_sent.fetch_add(chan_anns.len(), Ordering::AcqRel);
360 fn get_next_node_announcements(&self, _starting_point: Option<&PublicKey>, _batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
364 fn sync_routing_table(&self, _their_node_id: &PublicKey, _init_msg: &msgs::Init) {}
366 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), msgs::LightningError> {
370 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), msgs::LightningError> {
374 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), msgs::LightningError> {
378 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), msgs::LightningError> {
383 impl events::MessageSendEventsProvider for TestRoutingMessageHandler {
384 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
389 pub struct TestLogger {
392 pub lines: Mutex<HashMap<(String, String), usize>>,
396 pub fn new() -> TestLogger {
397 Self::with_id("".to_owned())
399 pub fn with_id(id: String) -> TestLogger {
403 lines: Mutex::new(HashMap::new())
406 pub fn enable(&mut self, level: Level) {
409 pub fn assert_log(&self, module: String, line: String, count: usize) {
410 let log_entries = self.lines.lock().unwrap();
411 assert_eq!(log_entries.get(&(module, line)), Some(&count));
414 /// Search for the number of occurrence of the logged lines which
415 /// 1. belongs to the specified module and
416 /// 2. contains `line` in it.
417 /// And asserts if the number of occurrences is the same with the given `count`
418 pub fn assert_log_contains(&self, module: String, line: String, count: usize) {
419 let log_entries = self.lines.lock().unwrap();
420 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
421 m == &module && l.contains(line.as_str())
422 }).map(|(_, c) | { c }).sum();
426 /// Search for the number of occurrences of logged lines which
427 /// 1. belong to the specified module and
428 /// 2. match the given regex pattern.
429 /// Assert that the number of occurrences equals the given `count`
430 pub fn assert_log_regex(&self, module: String, pattern: regex::Regex, count: usize) {
431 let log_entries = self.lines.lock().unwrap();
432 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
433 m == &module && pattern.is_match(&l)
434 }).map(|(_, c) | { c }).sum();
439 impl Logger for TestLogger {
440 fn log(&self, record: &Record) {
441 *self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1;
442 if self.level >= record.level {
443 println!("{:<5} {} [{} : {}, {}] {}", record.level.to_string(), self.id, record.module_path, record.file, record.line, record.args);
448 pub struct TestKeysInterface {
449 pub backing: keysinterface::KeysManager,
450 pub override_session_priv: Mutex<Option<[u8; 32]>>,
451 pub override_channel_id_priv: Mutex<Option<[u8; 32]>>,
452 pub disable_revocation_policy_check: bool,
453 revoked_commitments: Mutex<HashMap<[u8;32], Arc<Mutex<u64>>>>,
456 impl keysinterface::KeysInterface for TestKeysInterface {
457 type Signer = EnforcingSigner;
459 fn get_node_secret(&self) -> SecretKey { self.backing.get_node_secret() }
460 fn get_destination_script(&self) -> Script { self.backing.get_destination_script() }
461 fn get_shutdown_pubkey(&self) -> PublicKey { self.backing.get_shutdown_pubkey() }
462 fn get_channel_signer(&self, inbound: bool, channel_value_satoshis: u64) -> EnforcingSigner {
463 let keys = self.backing.get_channel_signer(inbound, channel_value_satoshis);
464 let revoked_commitment = self.make_revoked_commitment_cell(keys.commitment_seed);
465 EnforcingSigner::new_with_revoked(keys, revoked_commitment, self.disable_revocation_policy_check)
468 fn get_secure_random_bytes(&self) -> [u8; 32] {
469 let override_channel_id = self.override_channel_id_priv.lock().unwrap();
470 let override_session_key = self.override_session_priv.lock().unwrap();
471 if override_channel_id.is_some() && override_session_key.is_some() {
472 panic!("We don't know which override key to use!");
474 if let Some(key) = &*override_channel_id {
477 if let Some(key) = &*override_session_key {
480 self.backing.get_secure_random_bytes()
483 fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
484 let mut reader = std::io::Cursor::new(buffer);
486 let inner: InMemorySigner = Readable::read(&mut reader)?;
487 let revoked_commitment = self.make_revoked_commitment_cell(inner.commitment_seed);
489 let last_commitment_number = Readable::read(&mut reader)?;
493 last_commitment_number: Arc::new(Mutex::new(last_commitment_number)),
495 disable_revocation_policy_check: self.disable_revocation_policy_check,
499 fn sign_invoice(&self, invoice_preimage: Vec<u8>) -> Result<RecoverableSignature, ()> {
500 self.backing.sign_invoice(invoice_preimage)
505 impl TestKeysInterface {
506 pub fn new(seed: &[u8; 32], network: Network) -> Self {
507 let now = Duration::from_secs(genesis_block(network).header.time as u64);
509 backing: keysinterface::KeysManager::new(seed, now.as_secs(), now.subsec_nanos()),
510 override_session_priv: Mutex::new(None),
511 override_channel_id_priv: Mutex::new(None),
512 disable_revocation_policy_check: false,
513 revoked_commitments: Mutex::new(HashMap::new()),
516 pub fn derive_channel_keys(&self, channel_value_satoshis: u64, id: &[u8; 32]) -> EnforcingSigner {
517 let keys = self.backing.derive_channel_keys(channel_value_satoshis, id);
518 let revoked_commitment = self.make_revoked_commitment_cell(keys.commitment_seed);
519 EnforcingSigner::new_with_revoked(keys, revoked_commitment, self.disable_revocation_policy_check)
522 fn make_revoked_commitment_cell(&self, commitment_seed: [u8; 32]) -> Arc<Mutex<u64>> {
523 let mut revoked_commitments = self.revoked_commitments.lock().unwrap();
524 if !revoked_commitments.contains_key(&commitment_seed) {
525 revoked_commitments.insert(commitment_seed, Arc::new(Mutex::new(INITIAL_REVOKED_COMMITMENT_NUMBER)));
527 let cell = revoked_commitments.get(&commitment_seed).unwrap();
532 pub struct TestChainSource {
533 pub genesis_hash: BlockHash,
534 pub utxo_ret: Mutex<Result<TxOut, chain::AccessError>>,
535 pub watched_txn: Mutex<HashSet<(Txid, Script)>>,
536 pub watched_outputs: Mutex<HashSet<(OutPoint, Script)>>,
537 expectations: Mutex<Option<VecDeque<OnRegisterOutput>>>,
540 impl TestChainSource {
541 pub fn new(network: Network) -> Self {
542 let script_pubkey = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
544 genesis_hash: genesis_block(network).block_hash(),
545 utxo_ret: Mutex::new(Ok(TxOut { value: u64::max_value(), script_pubkey })),
546 watched_txn: Mutex::new(HashSet::new()),
547 watched_outputs: Mutex::new(HashSet::new()),
548 expectations: Mutex::new(None),
552 /// Sets an expectation that [`chain::Filter::register_output`] is called.
553 pub fn expect(&self, expectation: OnRegisterOutput) -> &Self {
554 self.expectations.lock().unwrap()
555 .get_or_insert_with(|| VecDeque::new())
556 .push_back(expectation);
561 impl chain::Access for TestChainSource {
562 fn get_utxo(&self, genesis_hash: &BlockHash, _short_channel_id: u64) -> Result<TxOut, chain::AccessError> {
563 if self.genesis_hash != *genesis_hash {
564 return Err(chain::AccessError::UnknownChain);
567 self.utxo_ret.lock().unwrap().clone()
571 impl chain::Filter for TestChainSource {
572 fn register_tx(&self, txid: &Txid, script_pubkey: &Script) {
573 self.watched_txn.lock().unwrap().insert((*txid, script_pubkey.clone()));
576 fn register_output(&self, output: WatchedOutput) -> Option<(usize, Transaction)> {
577 let dependent_tx = match &mut *self.expectations.lock().unwrap() {
579 Some(expectations) => match expectations.pop_front() {
581 panic!("Unexpected register_output: {:?}",
582 (output.outpoint, output.script_pubkey));
584 Some(expectation) => {
585 assert_eq!(output.outpoint, expectation.outpoint());
586 assert_eq!(&output.script_pubkey, expectation.script_pubkey());
592 self.watched_outputs.lock().unwrap().insert((output.outpoint, output.script_pubkey));
597 impl Drop for TestChainSource {
599 if std::thread::panicking() {
603 if let Some(expectations) = &*self.expectations.lock().unwrap() {
604 if !expectations.is_empty() {
605 panic!("Unsatisfied expectations: {:?}", expectations);
611 /// An expectation that [`chain::Filter::register_output`] was called with a transaction output and
612 /// returns an optional dependent transaction that spends the output in the same block.
613 pub struct OnRegisterOutput {
614 /// The transaction output to register.
615 pub with: TxOutReference,
617 /// A dependent transaction spending the output along with its position in the block.
618 pub returns: Option<(usize, Transaction)>,
621 /// A transaction output as identified by an index into a transaction's output list.
622 pub struct TxOutReference(pub Transaction, pub usize);
624 impl OnRegisterOutput {
625 fn outpoint(&self) -> OutPoint {
626 let txid = self.with.0.txid();
627 let index = self.with.1 as u16;
628 OutPoint { txid, index }
631 fn script_pubkey(&self) -> &Script {
632 let index = self.with.1;
633 &self.with.0.output[index].script_pubkey
637 impl core::fmt::Debug for OnRegisterOutput {
638 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
639 f.debug_struct("OnRegisterOutput")
640 .field("outpoint", &self.outpoint())
641 .field("script_pubkey", self.script_pubkey())