Merge pull request #1397 from jkczyz/2022-03-release-0.0.106 v0.0.106
authorMatt Corallo <649246+TheBlueMatt@users.noreply.github.com>
Sun, 3 Apr 2022 16:31:54 +0000 (16:31 +0000)
committerGitHub <noreply@github.com>
Sun, 3 Apr 2022 16:31:54 +0000 (16:31 +0000)
Cut 0.0.106

lightning-background-processor/src/lib.rs
lightning-persister/src/lib.rs
lightning/src/ln/channel.rs
lightning/src/ln/channelmanager.rs
lightning/src/routing/router.rs
lightning/src/routing/scoring.rs

index 22fef2661fa661d82884c047bb09697959841a15..73f420c98a429ddba67b20490bf9dbb060a9e034 100644 (file)
@@ -75,10 +75,13 @@ const PING_TIMER: u64 = 1;
 /// Prune the network graph of stale entries hourly.
 const NETWORK_PRUNE_TIMER: u64 = 60 * 60;
 
-/// Trait which handles persisting a [`ChannelManager`] to disk.
-///
-/// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
-pub trait ChannelManagerPersister<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
+#[cfg(not(test))]
+const FIRST_NETWORK_PRUNE_TIMER: u64 = 60;
+#[cfg(test)]
+const FIRST_NETWORK_PRUNE_TIMER: u64 = 1;
+
+/// Trait that handles persisting a [`ChannelManager`] and [`NetworkGraph`] to disk.
+pub trait Persister<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
 where
        M::Target: 'static + chain::Watch<Signer>,
        T::Target: 'static + BroadcasterInterface,
@@ -87,24 +90,11 @@ where
        L::Target: 'static + Logger,
 {
        /// Persist the given [`ChannelManager`] to disk, returning an error if persistence failed
-       /// (which will cause the [`BackgroundProcessor`] which called this method to exit.
-       ///
-       /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
+       /// (which will cause the [`BackgroundProcessor`] which called this method to exit).
        fn persist_manager(&self, channel_manager: &ChannelManager<Signer, M, T, K, F, L>) -> Result<(), std::io::Error>;
-}
 
-impl<Fun, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
-ChannelManagerPersister<Signer, M, T, K, F, L> for Fun where
-       M::Target: 'static + chain::Watch<Signer>,
-       T::Target: 'static + BroadcasterInterface,
-       K::Target: 'static + KeysInterface<Signer = Signer>,
-       F::Target: 'static + FeeEstimator,
-       L::Target: 'static + Logger,
-       Fun: Fn(&ChannelManager<Signer, M, T, K, F, L>) -> Result<(), std::io::Error>,
-{
-       fn persist_manager(&self, channel_manager: &ChannelManager<Signer, M, T, K, F, L>) -> Result<(), std::io::Error> {
-               self(channel_manager)
-       }
+       /// Persist the given [`NetworkGraph`] to disk, returning an error if persistence failed.
+       fn persist_graph(&self, network_graph: &NetworkGraph) -> Result<(), std::io::Error>;
 }
 
 /// Decorates an [`EventHandler`] with common functionality provided by standard [`EventHandler`]s.
@@ -141,17 +131,21 @@ impl BackgroundProcessor {
        /// documentation].
        ///
        /// The thread runs indefinitely unless the object is dropped, [`stop`] is called, or
-       /// `persist_manager` returns an error. In case of an error, the error is retrieved by calling
+       /// [`Persister::persist_manager`] returns an error. In case of an error, the error is retrieved by calling
        /// either [`join`] or [`stop`].
        ///
        /// # Data Persistence
        ///
-       /// `persist_manager` is responsible for writing out the [`ChannelManager`] to disk, and/or
+       /// [`Persister::persist_manager`] is responsible for writing out the [`ChannelManager`] to disk, and/or
        /// uploading to one or more backup services. See [`ChannelManager::write`] for writing out a
        /// [`ChannelManager`]. See [`FilesystemPersister::persist_manager`] for Rust-Lightning's
        /// provided implementation.
        ///
-       /// Typically, users should either implement [`ChannelManagerPersister`] to never return an
+       /// [`Persister::persist_graph`] is responsible for writing out the [`NetworkGraph`] to disk. See
+       /// [`NetworkGraph::write`] for writing out a [`NetworkGraph`]. See [`FilesystemPersister::persist_network_graph`]
+       /// for Rust-Lightning's provided implementation.
+       ///
+       /// Typically, users should either implement [`Persister::persist_manager`] to never return an
        /// error or call [`join`] and handle any error that may arise. For the latter case,
        /// `BackgroundProcessor` must be restarted by calling `start` again after handling the error.
        ///
@@ -168,7 +162,9 @@ impl BackgroundProcessor {
        /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
        /// [`ChannelManager::write`]: lightning::ln::channelmanager::ChannelManager#impl-Writeable
        /// [`FilesystemPersister::persist_manager`]: lightning_persister::FilesystemPersister::persist_manager
+       /// [`FilesystemPersister::persist_network_graph`]: lightning_persister::FilesystemPersister::persist_network_graph
        /// [`NetworkGraph`]: lightning::routing::network_graph::NetworkGraph
+       /// [`NetworkGraph::write`]: lightning::routing::network_graph::NetworkGraph#impl-Writeable
        pub fn start<
                Signer: 'static + Sign,
                CA: 'static + Deref + Send + Sync,
@@ -184,14 +180,14 @@ impl BackgroundProcessor {
                CMH: 'static + Deref + Send + Sync,
                RMH: 'static + Deref + Send + Sync,
                EH: 'static + EventHandler + Send,
-               CMP: 'static + Send + ChannelManagerPersister<Signer, CW, T, K, F, L>,
+               PS: 'static + Send + Persister<Signer, CW, T, K, F, L>,
                M: 'static + Deref<Target = ChainMonitor<Signer, CF, T, F, L, P>> + Send + Sync,
                CM: 'static + Deref<Target = ChannelManager<Signer, CW, T, K, F, L>> + Send + Sync,
                NG: 'static + Deref<Target = NetGraphMsgHandler<G, CA, L>> + Send + Sync,
                UMH: 'static + Deref + Send + Sync,
                PM: 'static + Deref<Target = PeerManager<Descriptor, CMH, RMH, L, UMH>> + Send + Sync,
        >(
-               persister: CMP, event_handler: EH, chain_monitor: M, channel_manager: CM,
+               persister: PS, event_handler: EH, chain_monitor: M, channel_manager: CM,
                net_graph_msg_handler: Option<NG>, peer_manager: PM, logger: L
        ) -> Self
        where
@@ -273,19 +269,29 @@ impl BackgroundProcessor {
                                // falling back to our usual hourly prunes. This avoids short-lived clients never
                                // pruning their network graph. We run once 60 seconds after startup before
                                // continuing our normal cadence.
-                               if last_prune_call.elapsed().as_secs() > if have_pruned { NETWORK_PRUNE_TIMER } else { 60 } {
+                               if last_prune_call.elapsed().as_secs() > if have_pruned { NETWORK_PRUNE_TIMER } else { FIRST_NETWORK_PRUNE_TIMER } {
                                        if let Some(ref handler) = net_graph_msg_handler {
                                                log_trace!(logger, "Pruning network graph of stale entries");
                                                handler.network_graph().remove_stale_channels();
+                                               if let Err(e) = persister.persist_graph(handler.network_graph()) {
+                                                       log_error!(logger, "Error: Failed to persist network graph, check your disk and permissions {}", e)
+                                               }
                                                last_prune_call = Instant::now();
                                                have_pruned = true;
                                        }
                                }
                        }
+
                        // After we exit, ensure we persist the ChannelManager one final time - this avoids
                        // some races where users quit while channel updates were in-flight, with
                        // ChannelMonitor update(s) persisted without a corresponding ChannelManager update.
-                       persister.persist_manager(&*channel_manager)
+                       persister.persist_manager(&*channel_manager)?;
+
+                       // Persist NetworkGraph on exit
+                       if let Some(ref handler) = net_graph_msg_handler {
+                               persister.persist_graph(handler.network_graph())?;
+                       }
+                       Ok(())
                });
                Self { stop_thread: stop_thread_clone, thread_handle: Some(handle) }
        }
@@ -343,9 +349,10 @@ mod tests {
        use bitcoin::blockdata::constants::genesis_block;
        use bitcoin::blockdata::transaction::{Transaction, TxOut};
        use bitcoin::network::constants::Network;
-       use lightning::chain::{BestBlock, Confirm, chainmonitor};
+       use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
+       use lightning::chain::{BestBlock, Confirm, chainmonitor, self};
        use lightning::chain::channelmonitor::ANTI_REORG_DELAY;
-       use lightning::chain::keysinterface::{InMemorySigner, Recipient, KeysInterface, KeysManager};
+       use lightning::chain::keysinterface::{InMemorySigner, Recipient, KeysInterface, KeysManager, Sign};
        use lightning::chain::transaction::OutPoint;
        use lightning::get_event_msg;
        use lightning::ln::channelmanager::{BREAKDOWN_TIMEOUT, ChainParameters, ChannelManager, SimpleArcChannelManager};
@@ -355,12 +362,14 @@ mod tests {
        use lightning::routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
        use lightning::util::config::UserConfig;
        use lightning::util::events::{Event, MessageSendEventsProvider, MessageSendEvent};
+       use lightning::util::logger::Logger;
        use lightning::util::ser::Writeable;
        use lightning::util::test_utils;
        use lightning_invoice::payment::{InvoicePayer, RetryAttempts};
        use lightning_invoice::utils::DefaultRouter;
        use lightning_persister::FilesystemPersister;
        use std::fs;
+       use std::ops::Deref;
        use std::path::PathBuf;
        use std::sync::{Arc, Mutex};
        use std::time::Duration;
@@ -402,6 +411,48 @@ mod tests {
                }
        }
 
+       struct Persister {
+               data_dir: String,
+               graph_error: Option<(std::io::ErrorKind, &'static str)>,
+               manager_error: Option<(std::io::ErrorKind, &'static str)>
+       }
+
+       impl Persister {
+               fn new(data_dir: String) -> Self {
+                       Self { data_dir, graph_error: None, manager_error: None }
+               }
+
+               fn with_graph_error(self, error: std::io::ErrorKind, message: &'static str) -> Self {
+                       Self { graph_error: Some((error, message)), ..self }
+               }
+
+               fn with_manager_error(self, error: std::io::ErrorKind, message: &'static str) -> Self {
+                       Self { manager_error: Some((error, message)), ..self }
+               }
+       }
+
+       impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L:Deref> super::Persister<Signer, M, T, K, F, L> for Persister where
+               M::Target: 'static + chain::Watch<Signer>,
+               T::Target: 'static + BroadcasterInterface,
+               K::Target: 'static + KeysInterface<Signer = Signer>,
+               F::Target: 'static + FeeEstimator,
+               L::Target: 'static + Logger,
+       {
+               fn persist_manager(&self, channel_manager: &ChannelManager<Signer, M, T, K, F, L>) -> Result<(), std::io::Error> {
+                       match self.manager_error {
+                               None => FilesystemPersister::persist_manager(self.data_dir.clone(), channel_manager),
+                               Some((error, message)) => Err(std::io::Error::new(error, message)),
+                       }
+               }
+
+               fn persist_graph(&self, network_graph: &NetworkGraph) -> Result<(), std::io::Error> {
+                       match self.graph_error {
+                               None => FilesystemPersister::persist_network_graph(self.data_dir.clone(), network_graph),
+                               Some((error, message)) => Err(std::io::Error::new(error, message)),
+                       }
+               }
+       }
+
        fn get_full_filepath(filepath: String, filename: String) -> String {
                let mut path = PathBuf::from(filepath);
                path.push(filename);
@@ -525,19 +576,20 @@ mod tests {
 
                // Initiate the background processors to watch each node.
                let data_dir = nodes[0].persister.get_data_dir();
-               let persister = move |node: &ChannelManager<InMemorySigner, Arc<ChainMonitor>, Arc<test_utils::TestBroadcaster>, Arc<KeysManager>, Arc<test_utils::TestFeeEstimator>, Arc<test_utils::TestLogger>>| FilesystemPersister::persist_manager(data_dir.clone(), node);
+               let persister = Persister::new(data_dir);
                let event_handler = |_: &_| {};
                let bg_processor = BackgroundProcessor::start(persister, event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].net_graph_msg_handler.clone(), nodes[0].peer_manager.clone(), nodes[0].logger.clone());
 
                macro_rules! check_persisted_data {
-                       ($node: expr, $filepath: expr, $expected_bytes: expr) => {
+                       ($node: expr, $filepath: expr) => {
+                               let mut expected_bytes = Vec::new();
                                loop {
-                                       $expected_bytes.clear();
-                                       match $node.write(&mut $expected_bytes) {
+                                       expected_bytes.clear();
+                                       match $node.write(&mut expected_bytes) {
                                                Ok(()) => {
                                                        match std::fs::read($filepath) {
                                                                Ok(bytes) => {
-                                                                       if bytes == $expected_bytes {
+                                                                       if bytes == expected_bytes {
                                                                                break
                                                                        } else {
                                                                                continue
@@ -554,8 +606,8 @@ mod tests {
 
                // Check that the initial channel manager data is persisted as expected.
                let filepath = get_full_filepath("test_background_processor_persister_0".to_string(), "manager".to_string());
-               let mut expected_bytes = Vec::new();
-               check_persisted_data!(nodes[0].node, filepath.clone(), expected_bytes);
+               check_persisted_data!(nodes[0].node, filepath.clone());
+
                loop {
                        if !nodes[0].node.get_persistence_condvar_value() { break }
                }
@@ -564,12 +616,18 @@ mod tests {
                nodes[0].node.force_close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
 
                // Check that the force-close updates are persisted.
-               let mut expected_bytes = Vec::new();
-               check_persisted_data!(nodes[0].node, filepath.clone(), expected_bytes);
+               check_persisted_data!(nodes[0].node, filepath.clone());
                loop {
                        if !nodes[0].node.get_persistence_condvar_value() { break }
                }
 
+               // Check network graph is persisted
+               let filepath = get_full_filepath("test_background_processor_persister_0".to_string(), "network_graph".to_string());
+               if let Some(ref handler) = nodes[0].net_graph_msg_handler {
+                       let network_graph = handler.network_graph();
+                       check_persisted_data!(network_graph, filepath.clone());
+               }
+
                assert!(bg_processor.stop().is_ok());
        }
 
@@ -579,7 +637,7 @@ mod tests {
                // `FRESHNESS_TIMER`.
                let nodes = create_nodes(1, "test_timer_tick_called".to_string());
                let data_dir = nodes[0].persister.get_data_dir();
-               let persister = move |node: &ChannelManager<InMemorySigner, Arc<ChainMonitor>, Arc<test_utils::TestBroadcaster>, Arc<KeysManager>, Arc<test_utils::TestFeeEstimator>, Arc<test_utils::TestLogger>>| FilesystemPersister::persist_manager(data_dir.clone(), node);
+               let persister = Persister::new(data_dir);
                let event_handler = |_: &_| {};
                let bg_processor = BackgroundProcessor::start(persister, event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].net_graph_msg_handler.clone(), nodes[0].peer_manager.clone(), nodes[0].logger.clone());
                loop {
@@ -596,12 +654,13 @@ mod tests {
        }
 
        #[test]
-       fn test_persist_error() {
+       fn test_channel_manager_persist_error() {
                // Test that if we encounter an error during manager persistence, the thread panics.
                let nodes = create_nodes(2, "test_persist_error".to_string());
                open_channel!(nodes[0], nodes[1], 100000);
 
-               let persister = |_: &_| Err(std::io::Error::new(std::io::ErrorKind::Other, "test"));
+               let data_dir = nodes[0].persister.get_data_dir();
+               let persister = Persister::new(data_dir).with_manager_error(std::io::ErrorKind::Other, "test");
                let event_handler = |_: &_| {};
                let bg_processor = BackgroundProcessor::start(persister, event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].net_graph_msg_handler.clone(), nodes[0].peer_manager.clone(), nodes[0].logger.clone());
                match bg_processor.join() {
@@ -613,19 +672,37 @@ mod tests {
                }
        }
 
+       #[test]
+       fn test_network_graph_persist_error() {
+               // Test that if we encounter an error during network graph persistence, an error gets returned.
+               let nodes = create_nodes(2, "test_persist_network_graph_error".to_string());
+               let data_dir = nodes[0].persister.get_data_dir();
+               let persister = Persister::new(data_dir).with_graph_error(std::io::ErrorKind::Other, "test");
+               let event_handler = |_: &_| {};
+               let bg_processor = BackgroundProcessor::start(persister, event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].net_graph_msg_handler.clone(), nodes[0].peer_manager.clone(), nodes[0].logger.clone());
+
+               match bg_processor.stop() {
+                       Ok(_) => panic!("Expected error persisting network graph"),
+                       Err(e) => {
+                               assert_eq!(e.kind(), std::io::ErrorKind::Other);
+                               assert_eq!(e.get_ref().unwrap().to_string(), "test");
+                       },
+               }
+       }
+
        #[test]
        fn test_background_event_handling() {
                let mut nodes = create_nodes(2, "test_background_event_handling".to_string());
                let channel_value = 100000;
                let data_dir = nodes[0].persister.get_data_dir();
-               let persister = move |node: &_| FilesystemPersister::persist_manager(data_dir.clone(), node);
+               let persister = Persister::new(data_dir.clone());
 
                // Set up a background event handler for FundingGenerationReady events.
                let (sender, receiver) = std::sync::mpsc::sync_channel(1);
                let event_handler = move |event: &Event| {
                        sender.send(handle_funding_generation_ready!(event, channel_value)).unwrap();
                };
-               let bg_processor = BackgroundProcessor::start(persister.clone(), event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].net_graph_msg_handler.clone(), nodes[0].peer_manager.clone(), nodes[0].logger.clone());
+               let bg_processor = BackgroundProcessor::start(persister, event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].net_graph_msg_handler.clone(), nodes[0].peer_manager.clone(), nodes[0].logger.clone());
 
                // Open a channel and check that the FundingGenerationReady event was handled.
                begin_open_channel!(nodes[0], nodes[1], channel_value);
@@ -649,7 +726,7 @@ mod tests {
                // Set up a background event handler for SpendableOutputs events.
                let (sender, receiver) = std::sync::mpsc::sync_channel(1);
                let event_handler = move |event: &Event| sender.send(event.clone()).unwrap();
-               let bg_processor = BackgroundProcessor::start(persister, event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].net_graph_msg_handler.clone(), nodes[0].peer_manager.clone(), nodes[0].logger.clone());
+               let bg_processor = BackgroundProcessor::start(Persister::new(data_dir), event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].net_graph_msg_handler.clone(), nodes[0].peer_manager.clone(), nodes[0].logger.clone());
 
                // Force close the channel and check that the SpendableOutputs event was handled.
                nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
@@ -675,7 +752,7 @@ mod tests {
 
                // Initiate the background processors to watch each node.
                let data_dir = nodes[0].persister.get_data_dir();
-               let persister = move |node: &ChannelManager<InMemorySigner, Arc<ChainMonitor>, Arc<test_utils::TestBroadcaster>, Arc<KeysManager>, Arc<test_utils::TestFeeEstimator>, Arc<test_utils::TestLogger>>| FilesystemPersister::persist_manager(data_dir.clone(), node);
+               let persister = Persister::new(data_dir);
                let scorer = Arc::new(Mutex::new(test_utils::TestScorer::with_penalty(0)));
                let router = DefaultRouter::new(Arc::clone(&nodes[0].network_graph), Arc::clone(&nodes[0].logger), random_seed_bytes);
                let invoice_payer = Arc::new(InvoicePayer::new(Arc::clone(&nodes[0].node), router, scorer, Arc::clone(&nodes[0].logger), |_: &_| {}, RetryAttempts(2)));
index ef914700a16302c0e5dacad1414d3e0e8c1eb03c..da64cb375da11d71f517bcd31c47c5686796b088 100644 (file)
@@ -16,6 +16,7 @@ extern crate libc;
 
 use bitcoin::hash_types::{BlockHash, Txid};
 use bitcoin::hashes::hex::{FromHex, ToHex};
+use lightning::routing::network_graph::NetworkGraph;
 use crate::util::DiskWriteable;
 use lightning::chain;
 use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
@@ -66,6 +67,12 @@ where
        }
 }
 
+impl DiskWriteable for NetworkGraph {
+       fn write_to_file(&self, writer: &mut fs::File) -> Result<(), std::io::Error> {
+               self.write(writer)
+       }
+}
+
 impl FilesystemPersister {
        /// Initialize a new FilesystemPersister and set the path to the individual channels'
        /// files.
@@ -103,6 +110,13 @@ impl FilesystemPersister {
                util::write_to_file(path, "manager".to_string(), manager)
        }
 
+       /// Write the provided `NetworkGraph` to the path provided at `FilesystemPersister`
+       /// initialization, within a file called "network_graph"
+       pub fn persist_network_graph(data_dir: String, network_graph: &NetworkGraph) -> Result<(), std::io::Error> {
+               let path = PathBuf::from(data_dir);
+               util::write_to_file(path, "network_graph".to_string(), network_graph)
+       }
+
        /// Read `ChannelMonitor`s from disk.
        pub fn read_channelmonitors<Signer: Sign, K: Deref> (
                &self, keys_manager: K
index 679ff82e0181d75e8331ccd66bad1ff588cd8f1c..9ccdf816ad398d764d599b62e45e0e1274391572 100644 (file)
@@ -6289,44 +6289,39 @@ impl<'a, Signer: Sign, K: Deref> ReadableArgs<(&'a K, u32)> for Channel<Signer>
 
 #[cfg(test)]
 mod tests {
-       use bitcoin::util::bip143;
-       use bitcoin::consensus::encode::serialize;
        use bitcoin::blockdata::script::{Script, Builder};
-       use bitcoin::blockdata::transaction::{Transaction, TxOut, SigHashType};
+       use bitcoin::blockdata::transaction::{Transaction, TxOut};
        use bitcoin::blockdata::constants::genesis_block;
        use bitcoin::blockdata::opcodes;
        use bitcoin::network::constants::Network;
-       use bitcoin::hashes::hex::FromHex;
        use hex;
-       use ln::{PaymentPreimage, PaymentHash};
+       use ln::PaymentHash;
        use ln::channelmanager::{HTLCSource, PaymentId};
-       use ln::channel::{Channel,InboundHTLCOutput,OutboundHTLCOutput,InboundHTLCState,OutboundHTLCState,HTLCOutputInCommitment,HTLCCandidate,HTLCInitiator,TxCreationKeys};
+       use ln::channel::{Channel, InboundHTLCOutput, OutboundHTLCOutput, InboundHTLCState, OutboundHTLCState, HTLCCandidate, HTLCInitiator};
        use ln::channel::MAX_FUNDING_SATOSHIS;
        use ln::features::InitFeatures;
        use ln::msgs::{ChannelUpdate, DataLossProtect, DecodeError, OptionalField, UnsignedChannelUpdate};
        use ln::script::ShutdownScript;
        use ln::chan_utils;
-       use ln::chan_utils::{ChannelPublicKeys, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters, htlc_success_tx_weight, htlc_timeout_tx_weight};
+       use ln::chan_utils::{htlc_success_tx_weight, htlc_timeout_tx_weight};
        use chain::BestBlock;
        use chain::chaininterface::{FeeEstimator,ConfirmationTarget};
-       use chain::keysinterface::{InMemorySigner, Recipient, KeyMaterial, KeysInterface, BaseSign};
+       use chain::keysinterface::{InMemorySigner, Recipient, KeyMaterial, KeysInterface};
        use chain::transaction::OutPoint;
        use util::config::UserConfig;
        use util::enforcing_trait_impls::EnforcingSigner;
        use util::errors::APIError;
        use util::test_utils;
        use util::test_utils::OnGetShutdownScriptpubkey;
-       use util::logger::Logger;
-       use bitcoin::secp256k1::{Secp256k1, Message, Signature, All};
+       use bitcoin::secp256k1::{Secp256k1, Signature};
        use bitcoin::secp256k1::ffi::Signature as FFISignature;
        use bitcoin::secp256k1::key::{SecretKey,PublicKey};
        use bitcoin::secp256k1::recovery::RecoverableSignature;
        use bitcoin::hashes::sha256::Hash as Sha256;
        use bitcoin::hashes::Hash;
-       use bitcoin::hash_types::{Txid, WPubkeyHash};
+       use bitcoin::hash_types::WPubkeyHash;
        use core::num::NonZeroU8;
        use bitcoin::bech32::u5;
-       use sync::Arc;
        use prelude::*;
 
        struct TestFeeEstimator {
@@ -6380,7 +6375,8 @@ mod tests {
                fn sign_invoice(&self, _hrp_bytes: &[u8], _invoice_data: &[u5], _recipient: Recipient) -> Result<RecoverableSignature, ()> { panic!(); }
        }
 
-       fn public_from_secret_hex(secp_ctx: &Secp256k1<All>, hex: &str) -> PublicKey {
+       #[cfg(not(feature = "grind_signatures"))]
+       fn public_from_secret_hex(secp_ctx: &Secp256k1<bitcoin::secp256k1::All>, hex: &str) -> PublicKey {
                PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode(hex).unwrap()[..]).unwrap())
        }
 
@@ -6669,6 +6665,19 @@ mod tests {
        #[cfg(not(feature = "grind_signatures"))]
        #[test]
        fn outbound_commitment_test() {
+               use bitcoin::util::bip143;
+               use bitcoin::consensus::encode::serialize;
+               use bitcoin::blockdata::transaction::SigHashType;
+               use bitcoin::hashes::hex::FromHex;
+               use bitcoin::hash_types::Txid;
+               use bitcoin::secp256k1::Message;
+               use chain::keysinterface::BaseSign;
+               use ln::PaymentPreimage;
+               use ln::channel::{HTLCOutputInCommitment ,TxCreationKeys};
+               use ln::chan_utils::{ChannelPublicKeys, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters};
+               use util::logger::Logger;
+               use sync::Arc;
+
                // Test vectors from BOLT 3 Appendices C and F (anchors):
                let feeest = TestFeeEstimator{fee_est: 15000};
                let logger : Arc<Logger> = Arc::new(test_utils::TestLogger::new());
index cfa2da06fd17bddb9167f14ec9b2efed6a51d7ff..7acd99e3eba491baca576de6e9282d2317907385 100644 (file)
@@ -498,6 +498,7 @@ impl core::hash::Hash for HTLCSource {
                }
        }
 }
+#[cfg(not(feature = "grind_signatures"))]
 #[cfg(test)]
 impl HTLCSource {
        pub fn dummy() -> Self {
index 9f202557ff7066d485e59c0ce0a9710ae687e1be..6584eb5fb55472aad318e4449cd965a6434ebda4 100644 (file)
@@ -511,6 +511,10 @@ impl<'a> PaymentPath<'a> {
                return result;
        }
 
+       fn get_cost_msat(&self) -> u64 {
+               self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
+       }
+
        // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
        // to change fees may result in an inconsistency.
        //
@@ -912,14 +916,20 @@ where L::Target: Logger {
                                        let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
                                                amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
 
+                                       #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
+                                       let may_overpay_to_meet_path_minimum_msat =
+                                               ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
+                                                 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
+                                                (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
+                                                 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
+
                                        // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
-                                       // bother considering this channel.
-                                       // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
-                                       // be only reduced later (not increased), so this channel should just be skipped
-                                       // as not sufficient.
-                                       if !over_path_minimum_msat && doesnt_exceed_cltv_delta_limit {
+                                       // bother considering this channel. If retrying with recommended_value_msat may
+                                       // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
+                                       // around again with a higher amount.
+                                       if contributes_sufficient_value && doesnt_exceed_cltv_delta_limit && may_overpay_to_meet_path_minimum_msat {
                                                hit_minimum_limit = true;
-                                       } else if contributes_sufficient_value && doesnt_exceed_cltv_delta_limit {
+                                       } else if contributes_sufficient_value && doesnt_exceed_cltv_delta_limit && over_path_minimum_msat {
                                                // Note that low contribution here (limited by available_liquidity_msat)
                                                // might violate htlc_minimum_msat on the hops which are next along the
                                                // payment path (upstream to the payee). To avoid that, we recompute
@@ -1390,7 +1400,7 @@ where L::Target: Logger {
                                        // If we weren't capped by hitting a liquidity limit on a channel in the path,
                                        // we'll probably end up picking the same path again on the next iteration.
                                        // Decrease the available liquidity of a hop in the middle of the path.
-                                       let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.candidate.short_channel_id();
+                                       let victim_scid = payment_path.hops[(payment_path.hops.len()) / 2].0.candidate.short_channel_id();
                                        log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
                                        let victim_liquidity = bookkept_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
                                        *victim_liquidity = 0;
@@ -1502,9 +1512,8 @@ where L::Target: Logger {
                                // prefer lower cost paths.
                                cur_route.sort_unstable_by(|a, b| {
                                        a.get_value_msat().cmp(&b.get_value_msat())
-                                               // Reverse ordering for fees, so we drop higher-fee paths first
-                                               .then_with(|| b.get_total_fee_paid_msat().saturating_add(b.get_path_penalty_msat())
-                                                       .cmp(&a.get_total_fee_paid_msat().saturating_add(a.get_path_penalty_msat())))
+                                               // Reverse ordering for cost, so we drop higher-cost paths first
+                                               .then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
                                });
 
                                // We should make sure that at least 1 path left.
@@ -1548,8 +1557,8 @@ where L::Target: Logger {
        }
 
        // Step (9).
-       // Select the best route by lowest total fee.
-       drawn_routes.sort_unstable_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
+       // Select the best route by lowest total cost.
+       drawn_routes.sort_unstable_by_key(|paths| paths.iter().map(|path| path.get_cost_msat()).sum::<u64>());
        let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
        for payment_path in drawn_routes.first().unwrap() {
                let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
index 459303f7d87f0c988293a2360798665570607955..b7aa996ce2efae9622208e1293dcebf8b1b3d8b9 100644 (file)
@@ -517,7 +517,7 @@ pub struct ProbabilisticScorerUsingTime<G: Deref<Target = NetworkGraph>, T: Time
 
 /// Parameters for configuring [`ProbabilisticScorer`].
 ///
-/// Used to configure a base penalty and a liquidity penalty, the sum of which is the channel
+/// Used to configure base, liquidity, and amount penalties, the sum of which comprises the channel
 /// penalty (i.e., the amount in msats willing to be paid to avoid routing through the channel).
 #[derive(Clone, Copy)]
 pub struct ProbabilisticScoringParameters {
@@ -529,9 +529,12 @@ pub struct ProbabilisticScoringParameters {
        /// A multiplier used in conjunction with the negative `log10` of the channel's success
        /// probability for a payment to determine the liquidity penalty.
        ///
-       /// The penalty is based in part by the knowledge learned from prior successful and unsuccessful
+       /// The penalty is based in part on the knowledge learned from prior successful and unsuccessful
        /// payments. This knowledge is decayed over time based on [`liquidity_offset_half_life`]. The
-       /// penalty is effectively limited to `2 * liquidity_penalty_multiplier_msat`.
+       /// penalty is effectively limited to `2 * liquidity_penalty_multiplier_msat` (corresponding to
+       /// lower bounding the success probability to `0.01`) when the amount falls within the
+       /// uncertainty bounds of the channel liquidity balance. Amounts above the upper bound will
+       /// result in a `u64::max_value` penalty, however.
        ///
        /// Default value: 40,000 msat
        ///
@@ -552,6 +555,25 @@ pub struct ProbabilisticScoringParameters {
        /// When built with the `no-std` feature, time will never elapse. Therefore, the channel
        /// liquidity knowledge will never decay except when the bounds cross.
        pub liquidity_offset_half_life: Duration,
+
+       /// A multiplier used in conjunction with a payment amount and the negative `log10` of the
+       /// channel's success probability for the payment to determine the amount penalty.
+       ///
+       /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
+       /// fees plus penalty) for large payments. The penalty is computed as the product of this
+       /// multiplier and `2^20`ths of the payment amount, weighted by the negative `log10` of the
+       /// success probability.
+       ///
+       /// `-log10(success_probability) * amount_penalty_multiplier_msat * amount_msat / 2^20`
+       ///
+       /// In practice, this means for 0.1 success probability (`-log10(0.1) == 1`) each `2^20`th of
+       /// the amount will result in a penalty of the multiplier. And, as the success probability
+       /// decreases, the negative `log10` weighting will increase dramatically. For higher success
+       /// probabilities, the multiplier will have a decreasing effect as the negative `log10` will
+       /// fall below `1`.
+       ///
+       /// Default value: 256 msat
+       pub amount_penalty_multiplier_msat: u64,
 }
 
 /// Accounting for channel liquidity balance uncertainty.
@@ -599,12 +621,25 @@ impl<G: Deref<Target = NetworkGraph>, T: Time> ProbabilisticScorerUsingTime<G, T
        }
 }
 
+impl ProbabilisticScoringParameters {
+       #[cfg(test)]
+       fn zero_penalty() -> Self {
+               Self {
+                       base_penalty_msat: 0,
+                       liquidity_penalty_multiplier_msat: 0,
+                       liquidity_offset_half_life: Duration::from_secs(3600),
+                       amount_penalty_multiplier_msat: 0,
+               }
+       }
+}
+
 impl Default for ProbabilisticScoringParameters {
        fn default() -> Self {
                Self {
                        base_penalty_msat: 500,
                        liquidity_penalty_multiplier_msat: 40_000,
                        liquidity_offset_half_life: Duration::from_secs(3600),
+                       amount_penalty_multiplier_msat: 256,
                }
        }
 }
@@ -662,27 +697,63 @@ impl<T: Time> ChannelLiquidity<T> {
        }
 }
 
+/// Bounds `-log10` to avoid excessive liquidity penalties for payments with low success
+/// probabilities.
+const NEGATIVE_LOG10_UPPER_BOUND: u64 = 2;
+
+/// The divisor used when computing the amount penalty.
+const AMOUNT_PENALTY_DIVISOR: u64 = 1 << 20;
+
 impl<L: Deref<Target = u64>, T: Time, U: Deref<Target = T>> DirectedChannelLiquidity<L, T, U> {
        /// Returns a penalty for routing the given HTLC `amount_msat` through the channel in this
        /// direction.
-       fn penalty_msat(&self, amount_msat: u64, liquidity_penalty_multiplier_msat: u64) -> u64 {
-               let max_penalty_msat = liquidity_penalty_multiplier_msat.saturating_mul(2);
+       fn penalty_msat(&self, amount_msat: u64, params: ProbabilisticScoringParameters) -> u64 {
                let max_liquidity_msat = self.max_liquidity_msat();
                let min_liquidity_msat = core::cmp::min(self.min_liquidity_msat(), max_liquidity_msat);
-               if amount_msat > max_liquidity_msat {
-                       max_penalty_msat
-               } else if amount_msat <= min_liquidity_msat {
+               if amount_msat <= min_liquidity_msat {
                        0
+               } else if amount_msat >= max_liquidity_msat {
+                       if amount_msat > max_liquidity_msat {
+                               u64::max_value()
+                       } else if max_liquidity_msat != self.capacity_msat {
+                               // Avoid using the failed channel on retry.
+                               u64::max_value()
+                       } else {
+                               // Equivalent to hitting the else clause below with the amount equal to the
+                               // effective capacity and without any certainty on the liquidity upper bound.
+                               let negative_log10_times_1024 = NEGATIVE_LOG10_UPPER_BOUND * 1024;
+                               self.combined_penalty_msat(amount_msat, negative_log10_times_1024, params)
+                       }
                } else {
                        let numerator = (max_liquidity_msat - amount_msat).saturating_add(1);
                        let denominator = (max_liquidity_msat - min_liquidity_msat).saturating_add(1);
-                       let penalty_msat = approx::negative_log10_times_1024(numerator, denominator)
-                               .saturating_mul(liquidity_penalty_multiplier_msat) / 1024;
-                       // Upper bound the penalty to ensure some channel is selected.
-                       penalty_msat.min(max_penalty_msat)
+                       let negative_log10_times_1024 =
+                               approx::negative_log10_times_1024(numerator, denominator);
+                       self.combined_penalty_msat(amount_msat, negative_log10_times_1024, params)
                }
        }
 
+       /// Computes the liquidity and amount penalties and adds them to the base penalty.
+       #[inline(always)]
+       fn combined_penalty_msat(
+               &self, amount_msat: u64, negative_log10_times_1024: u64,
+               params: ProbabilisticScoringParameters
+       ) -> u64 {
+               let liquidity_penalty_msat = {
+                       // Upper bound the liquidity penalty to ensure some channel is selected.
+                       let multiplier_msat = params.liquidity_penalty_multiplier_msat;
+                       let max_penalty_msat = multiplier_msat.saturating_mul(NEGATIVE_LOG10_UPPER_BOUND);
+                       (negative_log10_times_1024.saturating_mul(multiplier_msat) / 1024).min(max_penalty_msat)
+               };
+               let amount_penalty_msat = negative_log10_times_1024
+                       .saturating_mul(params.amount_penalty_multiplier_msat)
+                       .saturating_mul(amount_msat) / 1024 / AMOUNT_PENALTY_DIVISOR;
+
+               params.base_penalty_msat
+                       .saturating_add(liquidity_penalty_msat)
+                       .saturating_add(amount_penalty_msat)
+       }
+
        /// Returns the lower bound of the channel liquidity balance in this direction.
        fn min_liquidity_msat(&self) -> u64 {
                self.decayed_offset_msat(*self.min_liquidity_offset_msat)
@@ -752,14 +823,12 @@ impl<G: Deref<Target = NetworkGraph>, T: Time> Score for ProbabilisticScorerUsin
                &self, short_channel_id: u64, amount_msat: u64, capacity_msat: u64, source: &NodeId,
                target: &NodeId
        ) -> u64 {
-               let liquidity_penalty_multiplier_msat = self.params.liquidity_penalty_multiplier_msat;
                let liquidity_offset_half_life = self.params.liquidity_offset_half_life;
                self.channel_liquidities
                        .get(&short_channel_id)
                        .unwrap_or(&ChannelLiquidity::new())
                        .as_directed(source, target, capacity_msat, liquidity_offset_half_life)
-                       .penalty_msat(amount_msat, liquidity_penalty_multiplier_msat)
-                       .saturating_add(self.params.base_penalty_msat)
+                       .penalty_msat(amount_msat, self.params)
        }
 
        fn payment_path_failed(&mut self, path: &[&RouteHop], short_channel_id: u64) {
@@ -1737,7 +1806,8 @@ mod tests {
        fn increased_penalty_nearing_liquidity_upper_bound() {
                let network_graph = network_graph();
                let params = ProbabilisticScoringParameters {
-                       base_penalty_msat: 0, liquidity_penalty_multiplier_msat: 1_000, ..Default::default()
+                       liquidity_penalty_multiplier_msat: 1_000,
+                       ..ProbabilisticScoringParameters::zero_penalty()
                };
                let scorer = ProbabilisticScorer::new(params, &network_graph);
                let source = source_node_id();
@@ -1762,7 +1832,8 @@ mod tests {
                let last_updated = SinceEpoch::now();
                let network_graph = network_graph();
                let params = ProbabilisticScoringParameters {
-                       base_penalty_msat: 0, liquidity_penalty_multiplier_msat: 1_000, ..Default::default()
+                       liquidity_penalty_multiplier_msat: 1_000,
+                       ..ProbabilisticScoringParameters::zero_penalty()
                };
                let scorer = ProbabilisticScorer::new(params, &network_graph)
                        .with_channel(42,
@@ -1774,15 +1845,16 @@ mod tests {
 
                assert_eq!(scorer.channel_penalty_msat(42, 39, 100, &source, &target), 0);
                assert_ne!(scorer.channel_penalty_msat(42, 50, 100, &source, &target), 0);
-               assert_ne!(scorer.channel_penalty_msat(42, 50, 100, &source, &target), 2_000);
-               assert_eq!(scorer.channel_penalty_msat(42, 61, 100, &source, &target), 2_000);
+               assert_ne!(scorer.channel_penalty_msat(42, 50, 100, &source, &target), u64::max_value());
+               assert_eq!(scorer.channel_penalty_msat(42, 61, 100, &source, &target), u64::max_value());
        }
 
        #[test]
        fn does_not_further_penalize_own_channel() {
                let network_graph = network_graph();
                let params = ProbabilisticScoringParameters {
-                       base_penalty_msat: 0, liquidity_penalty_multiplier_msat: 1_000, ..Default::default()
+                       liquidity_penalty_multiplier_msat: 1_000,
+                       ..ProbabilisticScoringParameters::zero_penalty()
                };
                let mut scorer = ProbabilisticScorer::new(params, &network_graph);
                let sender = sender_node_id();
@@ -1803,7 +1875,8 @@ mod tests {
        fn sets_liquidity_lower_bound_on_downstream_failure() {
                let network_graph = network_graph();
                let params = ProbabilisticScoringParameters {
-                       base_penalty_msat: 0, liquidity_penalty_multiplier_msat: 1_000, ..Default::default()
+                       liquidity_penalty_multiplier_msat: 1_000,
+                       ..ProbabilisticScoringParameters::zero_penalty()
                };
                let mut scorer = ProbabilisticScorer::new(params, &network_graph);
                let source = source_node_id();
@@ -1825,7 +1898,8 @@ mod tests {
        fn sets_liquidity_upper_bound_on_failure() {
                let network_graph = network_graph();
                let params = ProbabilisticScoringParameters {
-                       base_penalty_msat: 0, liquidity_penalty_multiplier_msat: 1_000, ..Default::default()
+                       liquidity_penalty_multiplier_msat: 1_000,
+                       ..ProbabilisticScoringParameters::zero_penalty()
                };
                let mut scorer = ProbabilisticScorer::new(params, &network_graph);
                let source = source_node_id();
@@ -1839,15 +1913,16 @@ mod tests {
                scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), 42);
 
                assert_eq!(scorer.channel_penalty_msat(42, 250, 1_000, &source, &target), 300);
-               assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 2_000);
-               assert_eq!(scorer.channel_penalty_msat(42, 750, 1_000, &source, &target), 2_000);
+               assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), u64::max_value());
+               assert_eq!(scorer.channel_penalty_msat(42, 750, 1_000, &source, &target), u64::max_value());
        }
 
        #[test]
        fn reduces_liquidity_upper_bound_along_path_on_success() {
                let network_graph = network_graph();
                let params = ProbabilisticScoringParameters {
-                       base_penalty_msat: 0, liquidity_penalty_multiplier_msat: 1_000, ..Default::default()
+                       liquidity_penalty_multiplier_msat: 1_000,
+                       ..ProbabilisticScoringParameters::zero_penalty()
                };
                let mut scorer = ProbabilisticScorer::new(params, &network_graph);
                let sender = sender_node_id();
@@ -1871,9 +1946,9 @@ mod tests {
        fn decays_liquidity_bounds_over_time() {
                let network_graph = network_graph();
                let params = ProbabilisticScoringParameters {
-                       base_penalty_msat: 0,
                        liquidity_penalty_multiplier_msat: 1_000,
                        liquidity_offset_half_life: Duration::from_secs(10),
+                       ..ProbabilisticScoringParameters::zero_penalty()
                };
                let mut scorer = ProbabilisticScorer::new(params, &network_graph);
                let source = source_node_id();
@@ -1888,19 +1963,19 @@ mod tests {
                assert_eq!(scorer.channel_penalty_msat(42, 128, 1_024, &source, &target), 0);
                assert_eq!(scorer.channel_penalty_msat(42, 256, 1_024, &source, &target), 97);
                assert_eq!(scorer.channel_penalty_msat(42, 768, 1_024, &source, &target), 1_409);
-               assert_eq!(scorer.channel_penalty_msat(42, 896, 1_024, &source, &target), 2_000);
+               assert_eq!(scorer.channel_penalty_msat(42, 896, 1_024, &source, &target), u64::max_value());
 
                SinceEpoch::advance(Duration::from_secs(9));
                assert_eq!(scorer.channel_penalty_msat(42, 128, 1_024, &source, &target), 0);
                assert_eq!(scorer.channel_penalty_msat(42, 256, 1_024, &source, &target), 97);
                assert_eq!(scorer.channel_penalty_msat(42, 768, 1_024, &source, &target), 1_409);
-               assert_eq!(scorer.channel_penalty_msat(42, 896, 1_024, &source, &target), 2_000);
+               assert_eq!(scorer.channel_penalty_msat(42, 896, 1_024, &source, &target), u64::max_value());
 
                SinceEpoch::advance(Duration::from_secs(1));
                assert_eq!(scorer.channel_penalty_msat(42, 64, 1_024, &source, &target), 0);
                assert_eq!(scorer.channel_penalty_msat(42, 128, 1_024, &source, &target), 34);
                assert_eq!(scorer.channel_penalty_msat(42, 896, 1_024, &source, &target), 1_773);
-               assert_eq!(scorer.channel_penalty_msat(42, 960, 1_024, &source, &target), 2_000);
+               assert_eq!(scorer.channel_penalty_msat(42, 960, 1_024, &source, &target), u64::max_value());
 
                // Fully decay liquidity lower bound.
                SinceEpoch::advance(Duration::from_secs(10 * 7));
@@ -1923,9 +1998,9 @@ mod tests {
        fn decays_liquidity_bounds_without_shift_overflow() {
                let network_graph = network_graph();
                let params = ProbabilisticScoringParameters {
-                       base_penalty_msat: 0,
                        liquidity_penalty_multiplier_msat: 1_000,
                        liquidity_offset_half_life: Duration::from_secs(10),
+                       ..ProbabilisticScoringParameters::zero_penalty()
                };
                let mut scorer = ProbabilisticScorer::new(params, &network_graph);
                let source = source_node_id();
@@ -1948,9 +2023,9 @@ mod tests {
        fn restricts_liquidity_bounds_after_decay() {
                let network_graph = network_graph();
                let params = ProbabilisticScoringParameters {
-                       base_penalty_msat: 0,
                        liquidity_penalty_multiplier_msat: 1_000,
                        liquidity_offset_half_life: Duration::from_secs(10),
+                       ..ProbabilisticScoringParameters::zero_penalty()
                };
                let mut scorer = ProbabilisticScorer::new(params, &network_graph);
                let source = source_node_id();
@@ -1986,16 +2061,16 @@ mod tests {
        fn restores_persisted_liquidity_bounds() {
                let network_graph = network_graph();
                let params = ProbabilisticScoringParameters {
-                       base_penalty_msat: 0,
                        liquidity_penalty_multiplier_msat: 1_000,
                        liquidity_offset_half_life: Duration::from_secs(10),
+                       ..ProbabilisticScoringParameters::zero_penalty()
                };
                let mut scorer = ProbabilisticScorer::new(params, &network_graph);
                let source = source_node_id();
                let target = target_node_id();
 
                scorer.payment_path_failed(&payment_path_for_amount(500).iter().collect::<Vec<_>>(), 42);
-               assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 2_000);
+               assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), u64::max_value());
 
                SinceEpoch::advance(Duration::from_secs(10));
                assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 472);
@@ -2016,16 +2091,16 @@ mod tests {
        fn decays_persisted_liquidity_bounds() {
                let network_graph = network_graph();
                let params = ProbabilisticScoringParameters {
-                       base_penalty_msat: 0,
                        liquidity_penalty_multiplier_msat: 1_000,
                        liquidity_offset_half_life: Duration::from_secs(10),
+                       ..ProbabilisticScoringParameters::zero_penalty()
                };
                let mut scorer = ProbabilisticScorer::new(params, &network_graph);
                let source = source_node_id();
                let target = target_node_id();
 
                scorer.payment_path_failed(&payment_path_for_amount(500).iter().collect::<Vec<_>>(), 42);
-               assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 2_000);
+               assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), u64::max_value());
 
                let mut serialized_scorer = Vec::new();
                scorer.write(&mut serialized_scorer).unwrap();
@@ -2051,7 +2126,8 @@ mod tests {
                let target = target_node_id();
 
                let params = ProbabilisticScoringParameters {
-                       base_penalty_msat: 0, liquidity_penalty_multiplier_msat: 1_000, ..Default::default()
+                       liquidity_penalty_multiplier_msat: 1_000,
+                       ..ProbabilisticScoringParameters::zero_penalty()
                };
                let scorer = ProbabilisticScorer::new(params, &network_graph);
                assert_eq!(scorer.channel_penalty_msat(42, 128, 1_024, &source, &target), 58);
@@ -2063,6 +2139,29 @@ mod tests {
                assert_eq!(scorer.channel_penalty_msat(42, 128, 1_024, &source, &target), 558);
        }
 
+       #[test]
+       fn adds_amount_penalty_to_liquidity_penalty() {
+               let network_graph = network_graph();
+               let source = source_node_id();
+               let target = target_node_id();
+
+               let params = ProbabilisticScoringParameters {
+                       liquidity_penalty_multiplier_msat: 1_000,
+                       amount_penalty_multiplier_msat: 0,
+                       ..ProbabilisticScoringParameters::zero_penalty()
+               };
+               let scorer = ProbabilisticScorer::new(params, &network_graph);
+               assert_eq!(scorer.channel_penalty_msat(42, 512_000, 1_024_000, &source, &target), 300);
+
+               let params = ProbabilisticScoringParameters {
+                       liquidity_penalty_multiplier_msat: 1_000,
+                       amount_penalty_multiplier_msat: 256,
+                       ..ProbabilisticScoringParameters::zero_penalty()
+               };
+               let scorer = ProbabilisticScorer::new(params, &network_graph);
+               assert_eq!(scorer.channel_penalty_msat(42, 512_000, 1_024_000, &source, &target), 337);
+       }
+
        #[test]
        fn calculates_log10_without_overflowing_u64_max_value() {
                let network_graph = network_graph();
@@ -2070,7 +2169,8 @@ mod tests {
                let target = target_node_id();
 
                let params = ProbabilisticScoringParameters {
-                       base_penalty_msat: 0, ..Default::default()
+                       liquidity_penalty_multiplier_msat: 40_000,
+                       ..ProbabilisticScoringParameters::zero_penalty()
                };
                let scorer = ProbabilisticScorer::new(params, &network_graph);
                assert_eq!(