Merge pull request #3129 from optout21/splicing-msgs-update
[rust-lightning] / lightning / src / util / test_utils.rs
index 92d43193e305def0ee3624613770117322d5eb43..4b2c3c2e3742b747e56430451f37d2ea706f29dc 100644 (file)
@@ -25,7 +25,8 @@ use crate::sign;
 use crate::events;
 use crate::events::bump_transaction::{WalletSource, Utxo};
 use crate::ln::types::ChannelId;
-use crate::ln::channelmanager::{ChannelDetails, self};
+use crate::ln::channel_state::ChannelDetails;
+use crate::ln::channelmanager;
 #[cfg(test)]
 use crate::ln::chan_utils::CommitmentTransaction;
 use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
@@ -46,14 +47,16 @@ use crate::util::logger::{Logger, Level, Record};
 use crate::util::ser::{Readable, ReadableArgs, Writer, Writeable};
 use crate::util::persist::KVStore;
 
+use bitcoin::amount::Amount;
 use bitcoin::blockdata::constants::ChainHash;
 use bitcoin::blockdata::constants::genesis_block;
 use bitcoin::blockdata::transaction::{Transaction, TxOut};
 use bitcoin::blockdata::script::{Builder, Script, ScriptBuf};
 use bitcoin::blockdata::opcodes;
 use bitcoin::blockdata::block::Block;
-use bitcoin::network::constants::Network;
+use bitcoin::network::Network;
 use bitcoin::hash_types::{BlockHash, Txid};
+use bitcoin::hashes::Hash;
 use bitcoin::sighash::{SighashCache, EcdsaSighashType};
 
 use bitcoin::secp256k1::{PublicKey, Scalar, Secp256k1, SecretKey, self};
@@ -68,14 +71,16 @@ use core::time::Duration;
 use crate::sync::{Mutex, Arc};
 use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
 use core::mem;
-use bitcoin::bech32::u5;
+use bech32::u5;
 use crate::sign::{InMemorySigner, RandomBytes, Recipient, EntropySource, NodeSigner, SignerProvider};
 
 #[cfg(feature = "std")]
 use std::time::{SystemTime, UNIX_EPOCH};
-use bitcoin::psbt::PartiallySignedTransaction;
+use bitcoin::psbt::Psbt;
 use bitcoin::Sequence;
 
+use super::test_channel_signer::SignerOp;
+
 pub fn pubkey(byte: u8) -> PublicKey {
        let secp_ctx = Secp256k1::new();
        PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
@@ -247,10 +252,18 @@ impl<'a> MessageRouter for TestRouter<'a> {
        fn create_blinded_paths<
                T: secp256k1::Signing + secp256k1::Verification
        >(
-               &self, recipient: PublicKey, peers: Vec<ForwardNode>, secp_ctx: &Secp256k1<T>,
+               &self, recipient: PublicKey, peers: Vec<PublicKey>, secp_ctx: &Secp256k1<T>,
        ) -> Result<Vec<BlindedPath>, ()> {
                self.router.create_blinded_paths(recipient, peers, secp_ctx)
        }
+
+       fn create_compact_blinded_paths<
+               T: secp256k1::Signing + secp256k1::Verification
+       >(
+               &self, recipient: PublicKey, peers: Vec<ForwardNode>, secp_ctx: &Secp256k1<T>,
+       ) -> Result<Vec<BlindedPath>, ()> {
+               self.router.create_compact_blinded_paths(recipient, peers, secp_ctx)
+       }
 }
 
 impl<'a> Drop for TestRouter<'a> {
@@ -282,10 +295,16 @@ impl<'a> MessageRouter for TestMessageRouter<'a> {
        }
 
        fn create_blinded_paths<T: secp256k1::Signing + secp256k1::Verification>(
-               &self, recipient: PublicKey, peers: Vec<ForwardNode>, secp_ctx: &Secp256k1<T>,
+               &self, recipient: PublicKey, peers: Vec<PublicKey>, secp_ctx: &Secp256k1<T>,
        ) -> Result<Vec<BlindedPath>, ()> {
                self.inner.create_blinded_paths(recipient, peers, secp_ctx)
        }
+
+       fn create_compact_blinded_paths<T: secp256k1::Signing + secp256k1::Verification>(
+               &self, recipient: PublicKey, peers: Vec<ForwardNode>, secp_ctx: &Secp256k1<T>,
+       ) -> Result<Vec<BlindedPath>, ()> {
+               self.inner.create_compact_blinded_paths(recipient, peers, secp_ctx)
+       }
 }
 
 pub struct OnlyReadsKeysInterface {}
@@ -410,7 +429,7 @@ impl<'a> chain::Watch<TestChannelSigner> for TestChainMonitor<'a> {
 #[cfg(test)]
 struct JusticeTxData {
        justice_tx: Transaction,
-       value: u64,
+       value: Amount,
        commitment_number: u64,
 }
 
@@ -499,7 +518,7 @@ impl<Signer: sign::ecdsa::EcdsaChannelSigner> chainmonitor::Persist<Signer> for
                        while let Some(JusticeTxData { justice_tx, value, commitment_number }) = channel_state.front() {
                                let input_idx = 0;
                                let commitment_txid = justice_tx.input[input_idx].previous_output.txid;
-                               match data.sign_to_local_justice_tx(justice_tx.clone(), input_idx, *value, *commitment_number) {
+                               match data.sign_to_local_justice_tx(justice_tx.clone(), input_idx, value.to_sat(), *commitment_number) {
                                        Ok(signed_justice_tx) => {
                                                let dup = self.watchtower_state.lock().unwrap()
                                                        .get_mut(&funding_txo).unwrap()
@@ -528,12 +547,16 @@ pub struct TestPersister {
        ///
        /// [`ChannelMonitor`]: channelmonitor::ChannelMonitor
        pub offchain_monitor_updates: Mutex<HashMap<OutPoint, HashSet<u64>>>,
+       /// When we get an update_persisted_channel call with no ChannelMonitorUpdate, we insert the
+       /// monitor's funding outpoint here.
+       pub chain_sync_monitor_persistences: Mutex<VecDeque<OutPoint>>
 }
 impl TestPersister {
        pub fn new() -> Self {
                Self {
                        update_rets: Mutex::new(VecDeque::new()),
                        offchain_monitor_updates: Mutex::new(new_hash_map()),
+                       chain_sync_monitor_persistences: Mutex::new(VecDeque::new())
                }
        }
 
@@ -556,15 +579,18 @@ impl<Signer: sign::ecdsa::EcdsaChannelSigner> chainmonitor::Persist<Signer> for
                        ret = update_ret;
                }
 
-               if let Some(update) = update  {
+               if let Some(update) = update {
                        self.offchain_monitor_updates.lock().unwrap().entry(funding_txo).or_insert(new_hash_set()).insert(update.update_id);
+               } else {
+                       self.chain_sync_monitor_persistences.lock().unwrap().push_back(funding_txo);
                }
                ret
        }
 
        fn archive_persisted_channel(&self, funding_txo: OutPoint) {
-               // remove the channel from the offchain_monitor_updates map
+               // remove the channel from the offchain_monitor_updates and chain_sync_monitor_persistences.
                self.offchain_monitor_updates.lock().unwrap().remove(&funding_txo);
+               self.chain_sync_monitor_persistences.lock().unwrap().retain(|x| x != &funding_txo);
        }
 }
 
@@ -783,8 +809,8 @@ impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
                self.received_msg(wire::Message::Stfu(msg.clone()));
        }
        #[cfg(splicing)]
-       fn handle_splice(&self, _their_node_id: &PublicKey, msg: &msgs::Splice) {
-               self.received_msg(wire::Message::Splice(msg.clone()));
+       fn handle_splice_init(&self, _their_node_id: &PublicKey, msg: &msgs::SpliceInit) {
+               self.received_msg(wire::Message::SpliceInit(msg.clone()));
        }
        #[cfg(splicing)]
        fn handle_splice_ack(&self, _their_node_id: &PublicKey, msg: &msgs::SpliceAck) {
@@ -1170,7 +1196,7 @@ impl NodeSigner for TestNodeSigner {
                Ok(SharedSecret::new(other_key, &node_secret))
        }
 
-       fn sign_invoice(&self, _: &[u8], _: &[bitcoin::bech32::u5], _: Recipient) -> Result<bitcoin::secp256k1::ecdsa::RecoverableSignature, ()> {
+       fn sign_invoice(&self, _: &[u8], _: &[bech32::u5], _: Recipient) -> Result<bitcoin::secp256k1::ecdsa::RecoverableSignature, ()> {
                unreachable!()
        }
 
@@ -1198,6 +1224,7 @@ pub struct TestKeysInterface {
        enforcement_states: Mutex<HashMap<[u8;32], Arc<Mutex<EnforcementState>>>>,
        expectations: Mutex<Option<VecDeque<OnGetShutdownScriptpubkey>>>,
        pub unavailable_signers: Mutex<HashSet<[u8; 32]>>,
+       pub unavailable_signers_ops: Mutex<HashMap<[u8; 32], HashSet<SignerOp>>>,
 }
 
 impl EntropySource for TestKeysInterface {
@@ -1256,9 +1283,11 @@ impl SignerProvider for TestKeysInterface {
        fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> TestChannelSigner {
                let keys = self.backing.derive_channel_signer(channel_value_satoshis, channel_keys_id);
                let state = self.make_enforcement_state_cell(keys.commitment_seed);
-               let signer = TestChannelSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check);
-               if self.unavailable_signers.lock().unwrap().contains(&channel_keys_id) {
-                       signer.set_available(false);
+               let mut signer = TestChannelSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check);
+               if let Some(ops) = self.unavailable_signers_ops.lock().unwrap().get(&channel_keys_id) {
+                       for &op in ops {
+                               signer.disable_op(op);
+                       }
                }
                signer
        }
@@ -1299,6 +1328,7 @@ impl TestKeysInterface {
                        enforcement_states: Mutex::new(new_hash_map()),
                        expectations: Mutex::new(None),
                        unavailable_signers: Mutex::new(new_hash_set()),
+                       unavailable_signers_ops: Mutex::new(new_hash_map()),
                }
        }
 
@@ -1374,7 +1404,7 @@ impl TestChainSource {
                let script_pubkey = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
                Self {
                        chain_hash: ChainHash::using_genesis_block(network),
-                       utxo_ret: Mutex::new(UtxoResult::Sync(Ok(TxOut { value: u64::max_value(), script_pubkey }))),
+                       utxo_ret: Mutex::new(UtxoResult::Sync(Ok(TxOut { value: Amount::MAX, script_pubkey }))),
                        get_utxo_call_count: AtomicUsize::new(0),
                        watched_txn: Mutex::new(new_hash_set()),
                        watched_outputs: Mutex::new(new_hash_set()),
@@ -1505,7 +1535,7 @@ impl TestWalletSource {
                }
        }
 
-       pub fn add_utxo(&self, outpoint: bitcoin::OutPoint, value: u64) -> TxOut {
+       pub fn add_utxo(&self, outpoint: bitcoin::OutPoint, value: Amount) -> TxOut {
                let public_key = bitcoin::PublicKey::new(self.secret_key.public_key(&self.secp));
                let utxo = Utxo::new_p2pkh(outpoint, value, &public_key.pubkey_hash());
                self.utxos.borrow_mut().push(utxo.clone());
@@ -1533,15 +1563,15 @@ impl WalletSource for TestWalletSource {
                Ok(ScriptBuf::new_p2pkh(&public_key.pubkey_hash()))
        }
 
-       fn sign_psbt(&self, psbt: PartiallySignedTransaction) -> Result<Transaction, ()> {
-               let mut tx = psbt.extract_tx();
+       fn sign_psbt(&self, psbt: Psbt) -> Result<Transaction, ()> {
+               let mut tx = psbt.extract_tx_unchecked_fee_rate();
                let utxos = self.utxos.borrow();
                for i in 0..tx.input.len() {
                        if let Some(utxo) = utxos.iter().find(|utxo| utxo.outpoint == tx.input[i].previous_output) {
                                let sighash = SighashCache::new(&tx)
                                        .legacy_signature_hash(i, &utxo.output.script_pubkey, EcdsaSighashType::All as u32)
                                        .map_err(|_| ())?;
-                               let sig = self.secp.sign_ecdsa(&(*sighash.as_raw_hash()).into(), &self.secret_key);
+                               let sig = self.secp.sign_ecdsa(&secp256k1::Message::from_digest(sighash.to_byte_array()), &self.secret_key);
                                let bitcoin_sig = bitcoin::ecdsa::Signature { sig, hash_ty: EcdsaSighashType::All };
                                tx.input[i].script_sig = Builder::new()
                                        .push_slice(&bitcoin_sig.serialize())