Remove KeysInterface trait.
[rust-lightning] / fuzz / src / full_stack.rs
index fbe854e01c04e6a1d0ce36019773b130a02696ec..2af7009eb687d995641e40dadf5fd68f74f4f6fa 100644 (file)
@@ -33,14 +33,14 @@ use lightning::chain::{BestBlock, ChannelMonitorUpdateStatus, Confirm, Listen};
 use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
 use lightning::chain::chainmonitor;
 use lightning::chain::transaction::OutPoint;
-use lightning::chain::keysinterface::{InMemorySigner, Recipient, KeyMaterial, KeysInterface};
+use lightning::chain::keysinterface::{InMemorySigner, Recipient, KeyMaterial, EntropySource, NodeSigner, SignerProvider};
 use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
-use lightning::ln::channelmanager::{ChainParameters, ChannelManager, PaymentId};
+use lightning::ln::channelmanager::{ChainParameters, ChannelDetails, ChannelManager, PaymentId};
 use lightning::ln::peer_handler::{MessageHandler,PeerManager,SocketDescriptor,IgnoringMessageHandler};
-use lightning::ln::msgs::DecodeError;
+use lightning::ln::msgs::{self, DecodeError};
 use lightning::ln::script::ShutdownScript;
 use lightning::routing::gossip::{P2PGossipSync, NetworkGraph};
-use lightning::routing::router::{find_route, PaymentParameters, RouteParameters};
+use lightning::routing::router::{find_route, InFlightHtlcs, PaymentParameters, Route, RouteHop, RouteParameters, Router};
 use lightning::routing::scoring::FixedPenaltyScorer;
 use lightning::util::config::UserConfig;
 use lightning::util::errors::APIError;
@@ -127,6 +127,24 @@ impl FeeEstimator for FuzzEstimator {
        }
 }
 
+struct FuzzRouter {}
+
+impl Router for FuzzRouter {
+       fn find_route(
+               &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
+               _inflight_htlcs: &InFlightHtlcs
+       ) -> Result<Route, msgs::LightningError> {
+               Err(msgs::LightningError {
+                       err: String::from("Not implemented"),
+                       action: msgs::ErrorAction::IgnoreError
+               })
+       }
+       fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
+       fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
+       fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
+       fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
+}
+
 struct TestBroadcaster {
        txn_broadcasted: Mutex<Vec<Transaction>>,
 }
@@ -162,13 +180,13 @@ impl<'a> std::hash::Hash for Peer<'a> {
        }
 }
 
-type ChannelMan = ChannelManager<
+type ChannelMan<'a> = ChannelManager<
        Arc<chainmonitor::ChainMonitor<EnforcingSigner, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<TestPersister>>>,
-       Arc<TestBroadcaster>, Arc<KeyProvider>, Arc<FuzzEstimator>, Arc<dyn Logger>>;
-type PeerMan<'a> = PeerManager<Peer<'a>, Arc<ChannelMan>, Arc<P2PGossipSync<Arc<NetworkGraph<Arc<dyn Logger>>>, Arc<dyn chain::Access>, Arc<dyn Logger>>>, IgnoringMessageHandler, Arc<dyn Logger>, IgnoringMessageHandler>;
+       Arc<TestBroadcaster>, Arc<KeyProvider>, Arc<FuzzEstimator>, &'a FuzzRouter, Arc<dyn Logger>>;
+type PeerMan<'a> = PeerManager<Peer<'a>, Arc<ChannelMan<'a>>, Arc<P2PGossipSync<Arc<NetworkGraph<Arc<dyn Logger>>>, Arc<dyn chain::Access>, Arc<dyn Logger>>>, IgnoringMessageHandler, Arc<dyn Logger>, IgnoringMessageHandler>;
 
 struct MoneyLossDetector<'a> {
-       manager: Arc<ChannelMan>,
+       manager: Arc<ChannelMan<'a>>,
        monitor: Arc<chainmonitor::ChainMonitor<EnforcingSigner, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<TestPersister>>>,
        handler: PeerMan<'a>,
 
@@ -182,7 +200,7 @@ struct MoneyLossDetector<'a> {
 }
 impl<'a> MoneyLossDetector<'a> {
        pub fn new(peers: &'a RefCell<[bool; 256]>,
-                  manager: Arc<ChannelMan>,
+                  manager: Arc<ChannelMan<'a>>,
                   monitor: Arc<chainmonitor::ChainMonitor<EnforcingSigner, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<TestPersister>>>,
                   handler: PeerMan<'a>) -> Self {
                MoneyLossDetector {
@@ -265,13 +283,25 @@ struct KeyProvider {
        counter: AtomicU64,
        signer_state: RefCell<HashMap<u8, (bool, Arc<Mutex<EnforcementState>>)>>
 }
-impl KeysInterface for KeyProvider {
-       type Signer = EnforcingSigner;
 
+impl EntropySource for KeyProvider {
+       fn get_secure_random_bytes(&self) -> [u8; 32] {
+               let ctr = self.counter.fetch_add(1, Ordering::Relaxed);
+               [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+                       (ctr >> 8*7) as u8, (ctr >> 8*6) as u8, (ctr >> 8*5) as u8, (ctr >> 8*4) as u8, (ctr >> 8*3) as u8, (ctr >> 8*2) as u8, (ctr >> 8*1) as u8, 14, (ctr >> 8*0) as u8]
+       }
+}
+
+impl NodeSigner for KeyProvider {
        fn get_node_secret(&self, _recipient: Recipient) -> Result<SecretKey, ()> {
                Ok(self.node_secret.clone())
        }
 
+       fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
+               let secp_ctx = Secp256k1::signing_only();
+               Ok(PublicKey::from_secret_key(&secp_ctx, &self.get_node_secret(recipient)?))
+       }
+
        fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()> {
                let mut node_secret = self.get_node_secret(recipient)?;
                if let Some(tweak) = tweak {
@@ -284,19 +314,13 @@ impl KeysInterface for KeyProvider {
                self.inbound_payment_key.clone()
        }
 
-       fn get_destination_script(&self) -> Script {
-               let secp_ctx = Secp256k1::signing_only();
-               let channel_monitor_claim_key = SecretKey::from_slice(&hex::decode("0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap()[..]).unwrap();
-               let our_channel_monitor_claim_key_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize());
-               Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_monitor_claim_key_hash[..]).into_script()
+       fn sign_invoice(&self, _hrp_bytes: &[u8], _invoice_data: &[u5], _recipient: Recipient) -> Result<RecoverableSignature, ()> {
+               unreachable!()
        }
+}
 
-       fn get_shutdown_scriptpubkey(&self) -> ShutdownScript {
-               let secp_ctx = Secp256k1::signing_only();
-               let secret_key = SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]).unwrap();
-               let pubkey_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &secret_key).serialize());
-               ShutdownScript::new_p2wpkh(&pubkey_hash)
-       }
+impl SignerProvider for KeyProvider {
+       type Signer = EnforcingSigner;
 
        fn generate_channel_keys_id(&self, inbound: bool, _channel_value_satoshis: u64, _user_channel_id: u128) -> [u8; 32] {
                let ctr = self.counter.fetch_add(1, Ordering::Relaxed) as u8;
@@ -337,12 +361,6 @@ impl KeysInterface for KeyProvider {
                }, state, false)
        }
 
-       fn get_secure_random_bytes(&self) -> [u8; 32] {
-               let ctr = self.counter.fetch_add(1, Ordering::Relaxed);
-               [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-               (ctr >> 8*7) as u8, (ctr >> 8*6) as u8, (ctr >> 8*5) as u8, (ctr >> 8*4) as u8, (ctr >> 8*3) as u8, (ctr >> 8*2) as u8, (ctr >> 8*1) as u8, 14, (ctr >> 8*0) as u8]
-       }
-
        fn read_chan_signer(&self, mut data: &[u8]) -> Result<EnforcingSigner, DecodeError> {
                let inner: InMemorySigner = ReadableArgs::read(&mut data, self.node_secret.clone())?;
                let state = Arc::new(Mutex::new(EnforcementState::new()));
@@ -354,8 +372,18 @@ impl KeysInterface for KeyProvider {
                ))
        }
 
-       fn sign_invoice(&self, _hrp_bytes: &[u8], _invoice_data: &[u5], _recipient: Recipient) -> Result<RecoverableSignature, ()> {
-               unreachable!()
+       fn get_destination_script(&self) -> Script {
+               let secp_ctx = Secp256k1::signing_only();
+               let channel_monitor_claim_key = SecretKey::from_slice(&hex::decode("0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap()[..]).unwrap();
+               let our_channel_monitor_claim_key_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize());
+               Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_monitor_claim_key_hash[..]).into_script()
+       }
+
+       fn get_shutdown_scriptpubkey(&self) -> ShutdownScript {
+               let secp_ctx = Secp256k1::signing_only();
+               let secret_key = SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]).unwrap();
+               let pubkey_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &secret_key).serialize());
+               ShutdownScript::new_p2wpkh(&pubkey_hash)
        }
 }
 
@@ -368,6 +396,7 @@ pub fn do_test(data: &[u8], logger: &Arc<dyn Logger>) {
        let fee_est = Arc::new(FuzzEstimator {
                input: input.clone(),
        });
+       let router = FuzzRouter {};
 
        macro_rules! get_slice {
                ($len: expr) => {
@@ -412,8 +441,8 @@ pub fn do_test(data: &[u8], logger: &Arc<dyn Logger>) {
                network,
                best_block: BestBlock::from_genesis(network),
        };
-       let channelmanager = Arc::new(ChannelManager::new(fee_est.clone(), monitor.clone(), broadcast.clone(), Arc::clone(&logger), keys_manager.clone(), config, params));
-       // Adding new calls to `KeysInterface::get_secure_random_bytes` during startup can change all the
+       let channelmanager = Arc::new(ChannelManager::new(fee_est.clone(), monitor.clone(), broadcast.clone(), &router, Arc::clone(&logger), keys_manager.clone(), config, params));
+       // Adding new calls to `EntropySource::get_secure_random_bytes` during startup can change all the
        // keys subsequently generated in this test. Rather than regenerating all the messages manually,
        // it's easier to just increment the counter here so the keys don't change.
        keys_manager.counter.fetch_sub(3, Ordering::AcqRel);
@@ -659,7 +688,7 @@ pub fn do_test(data: &[u8], logger: &Arc<dyn Logger>) {
                                Event::FundingGenerationReady { temporary_channel_id, counterparty_node_id, channel_value_satoshis, output_script, .. } => {
                                        pending_funding_generation.push((temporary_channel_id, counterparty_node_id, channel_value_satoshis, output_script));
                                },
-                               Event::PaymentReceived { payment_hash, .. } => {
+                               Event::PaymentClaimable { payment_hash, .. } => {
                                        //TODO: enhance by fetching random amounts from fuzz input?
                                        payments_received.push(payment_hash);
                                },