Merge pull request #1476 from tnull/2022-05-maximum-path-length
authorMatt Corallo <649246+TheBlueMatt@users.noreply.github.com>
Wed, 18 May 2022 19:22:42 +0000 (19:22 +0000)
committerGitHub <noreply@github.com>
Wed, 18 May 2022 19:22:42 +0000 (19:22 +0000)
Consider maximum path length during path finding.

fuzz/src/peer_crypt.rs
lightning-background-processor/src/lib.rs
lightning-invoice/src/lib.rs
lightning-invoice/src/payment.rs
lightning-invoice/src/time_utils.rs [new symlink]
lightning/src/ln/peer_channel_encryptor.rs
lightning/src/ln/peer_handler.rs
lightning/src/routing/scoring.rs
lightning/src/util/mod.rs
lightning/src/util/time.rs [new file with mode: 0644]

index 9bef432982497af54dc5c0f9912e22558f79f30b..de0443ebd5b2bd3eea3e4b117442620eae57f46d 100644 (file)
@@ -9,7 +9,7 @@
 
 use lightning::ln::peer_channel_encryptor::PeerChannelEncryptor;
 
-use bitcoin::secp256k1::{PublicKey,SecretKey};
+use bitcoin::secp256k1::{Secp256k1, PublicKey, SecretKey};
 
 use utils::test_logger;
 
@@ -35,6 +35,8 @@ pub fn do_test(data: &[u8]) {
                }
        }
 
+       let secp_ctx = Secp256k1::signing_only();
+
        let our_network_key = match SecretKey::from_slice(get_slice!(32)) {
                Ok(key) => key,
                Err(_) => return,
@@ -50,16 +52,16 @@ pub fn do_test(data: &[u8]) {
                        Err(_) => return,
                };
                let mut crypter = PeerChannelEncryptor::new_outbound(their_pubkey, ephemeral_key);
-               crypter.get_act_one();
-               match crypter.process_act_two(get_slice!(50), &our_network_key) {
+               crypter.get_act_one(&secp_ctx);
+               match crypter.process_act_two(get_slice!(50), &our_network_key, &secp_ctx) {
                        Ok(_) => {},
                        Err(_) => return,
                }
                assert!(crypter.is_ready_for_encryption());
                crypter
        } else {
-               let mut crypter = PeerChannelEncryptor::new_inbound(&our_network_key);
-               match crypter.process_act_one_with_keys(get_slice!(50), &our_network_key, ephemeral_key) {
+               let mut crypter = PeerChannelEncryptor::new_inbound(&our_network_key, &secp_ctx);
+               match crypter.process_act_one_with_keys(get_slice!(50), &our_network_key, ephemeral_key, &secp_ctx) {
                        Ok(_) => {},
                        Err(_) => return,
                }
index ef37e5f9f9f75dd87fe49ec2a6687b7fe001b02c..dab376178488654d70322155400c0bd263b740a4 100644 (file)
@@ -379,7 +379,7 @@ mod tests {
        use lightning::util::ser::Writeable;
        use lightning::util::test_utils;
        use lightning::util::persist::KVStorePersister;
-       use lightning_invoice::payment::{InvoicePayer, RetryAttempts};
+       use lightning_invoice::payment::{InvoicePayer, Retry};
        use lightning_invoice::utils::DefaultRouter;
        use lightning_persister::FilesystemPersister;
        use std::fs;
@@ -801,7 +801,7 @@ mod tests {
                let data_dir = nodes[0].persister.get_data_dir();
                let persister = Arc::new(Persister::new(data_dir));
                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, Arc::clone(&nodes[0].scorer), Arc::clone(&nodes[0].logger), |_: &_| {}, RetryAttempts(2)));
+               let invoice_payer = Arc::new(InvoicePayer::new(Arc::clone(&nodes[0].node), router, Arc::clone(&nodes[0].scorer), Arc::clone(&nodes[0].logger), |_: &_| {}, Retry::Attempts(2)));
                let event_handler = Arc::clone(&invoice_payer);
                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(), Some(nodes[0].scorer.clone()));
                assert!(bg_processor.stop().is_ok());
index 616ea99f0fe253cf2275862b1a63e6f0db3232f2..9fcb4af1b624257b6818d1c121c4dd9f7c6c6eaa 100644 (file)
@@ -25,6 +25,8 @@ compile_error!("at least one of the `std` or `no-std` features must be enabled")
 pub mod payment;
 pub mod utils;
 
+pub(crate) mod time_utils;
+
 extern crate bech32;
 extern crate bitcoin_hashes;
 #[macro_use] extern crate lightning;
index 6b79a0123d9e872cc3dcebdea7905c5b6d8613b2..d6a3abb0ddf60c8f8c0d47af92c30a7ca695e904 100644 (file)
@@ -45,7 +45,7 @@
 //! # use lightning::util::logger::{Logger, Record};
 //! # use lightning::util::ser::{Writeable, Writer};
 //! # use lightning_invoice::Invoice;
-//! # use lightning_invoice::payment::{InvoicePayer, Payer, RetryAttempts, Router};
+//! # use lightning_invoice::payment::{InvoicePayer, Payer, Retry, Router};
 //! # use secp256k1::PublicKey;
 //! # use std::cell::RefCell;
 //! # use std::ops::Deref;
 //! # let router = FakeRouter {};
 //! # let scorer = RefCell::new(FakeScorer {});
 //! # let logger = FakeLogger {};
-//! let invoice_payer = InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
+//! let invoice_payer = InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
 //!
 //! let invoice = "...";
 //! if let Ok(invoice) = invoice.parse::<Invoice>() {
@@ -146,10 +146,13 @@ use lightning::routing::scoring::{LockableScore, Score};
 use lightning::routing::router::{PaymentParameters, Route, RouteParameters};
 use lightning::util::events::{Event, EventHandler};
 use lightning::util::logger::Logger;
+use time_utils::Time;
 use crate::sync::Mutex;
 
 use secp256k1::PublicKey;
 
+use core::fmt;
+use core::fmt::{Debug, Display, Formatter};
 use core::ops::Deref;
 use core::time::Duration;
 #[cfg(feature = "std")]
@@ -160,7 +163,17 @@ use std::time::SystemTime;
 /// See [module-level documentation] for details.
 ///
 /// [module-level documentation]: crate::payment
-pub struct InvoicePayer<P: Deref, R, S: Deref, L: Deref, E: EventHandler>
+pub type InvoicePayer<P, R, S, L, E> = InvoicePayerUsingTime::<P, R, S, L, E, ConfiguredTime>;
+
+#[cfg(not(feature = "no-std"))]
+type ConfiguredTime = std::time::Instant;
+#[cfg(feature = "no-std")]
+use time_utils;
+#[cfg(feature = "no-std")]
+type ConfiguredTime = time_utils::Eternity;
+
+/// (C-not exported) generally all users should use the [`InvoicePayer`] type alias.
+pub struct InvoicePayerUsingTime<P: Deref, R, S: Deref, L: Deref, E: EventHandler, T: Time>
 where
        P::Target: Payer,
        R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
@@ -173,8 +186,42 @@ where
        logger: L,
        event_handler: E,
        /// Caches the overall attempts at making a payment, which is updated prior to retrying.
-       payment_cache: Mutex<HashMap<PaymentHash, usize>>,
-       retry_attempts: RetryAttempts,
+       payment_cache: Mutex<HashMap<PaymentHash, PaymentAttempts<T>>>,
+       retry: Retry,
+}
+
+/// Storing minimal payment attempts information required for determining if a outbound payment can
+/// be retried.
+#[derive(Clone, Copy)]
+struct PaymentAttempts<T: Time> {
+       /// This count will be incremented only after the result of the attempt is known. When it's 0,
+       /// it means the result of the first attempt is now known yet.
+       count: usize,
+       /// This field is only used when retry is [`Retry::Timeout`] which is only build with feature std
+       first_attempted_at: T
+}
+
+impl<T: Time> PaymentAttempts<T> {
+       fn new() -> Self {
+               PaymentAttempts {
+                       count: 0,
+                       first_attempted_at: T::now()
+               }
+       }
+}
+
+impl<T: Time> Display for PaymentAttempts<T> {
+       fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
+               #[cfg(feature = "no-std")]
+               return write!( f, "attempts: {}", self.count);
+               #[cfg(not(feature = "no-std"))]
+               return write!(
+                       f,
+                       "attempts: {}, duration: {}s",
+                       self.count,
+                       T::now().duration_since(self.first_attempted_at).as_secs()
+               );
+       }
 }
 
 /// A trait defining behavior of an [`Invoice`] payer.
@@ -211,13 +258,33 @@ pub trait Router<S: Score> {
        ) -> Result<Route, LightningError>;
 }
 
-/// Number of attempts to retry payment path failures for an [`Invoice`].
+/// Strategies available to retry payment path failures for an [`Invoice`].
 ///
-/// Note that this is the number of *path* failures, not full payment retries. For multi-path
-/// payments, if this is less than the total number of paths, we will never even retry all of the
-/// payment's paths.
 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
-pub struct RetryAttempts(pub usize);
+pub enum Retry {
+       /// Max number of attempts to retry payment.
+       ///
+       /// Note that this is the number of *path* failures, not full payment retries. For multi-path
+       /// payments, if this is less than the total number of paths, we will never even retry all of the
+       /// payment's paths.
+       Attempts(usize),
+       #[cfg(feature = "std")]
+       /// Time elapsed before abandoning retries for a payment.
+       Timeout(Duration),
+}
+
+impl Retry {
+       fn is_retryable_now<T: Time>(&self, attempts: &PaymentAttempts<T>) -> bool {
+               match (self, attempts) {
+                       (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
+                               max_retry_count >= &count
+                       },
+                       #[cfg(feature = "std")]
+                       (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. } ) =>
+                               *max_duration >= T::now().duration_since(*first_attempted_at),
+               }
+       }
+}
 
 /// An error that may occur when making a payment.
 #[derive(Clone, Debug)]
@@ -230,7 +297,7 @@ pub enum PaymentError {
        Sending(PaymentSendFailure),
 }
 
-impl<P: Deref, R, S: Deref, L: Deref, E: EventHandler> InvoicePayer<P, R, S, L, E>
+impl<P: Deref, R, S: Deref, L: Deref, E: EventHandler, T: Time> InvoicePayerUsingTime<P, R, S, L, E, T>
 where
        P::Target: Payer,
        R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
@@ -240,9 +307,9 @@ where
        /// Creates an invoice payer that retries failed payment paths.
        ///
        /// Will forward any [`Event::PaymentPathFailed`] events to the decorated `event_handler` once
-       /// `retry_attempts` has been exceeded for a given [`Invoice`].
+       /// `retry` has been exceeded for a given [`Invoice`].
        pub fn new(
-               payer: P, router: R, scorer: S, logger: L, event_handler: E, retry_attempts: RetryAttempts
+               payer: P, router: R, scorer: S, logger: L, event_handler: E, retry: Retry
        ) -> Self {
                Self {
                        payer,
@@ -251,7 +318,7 @@ where
                        logger,
                        event_handler,
                        payment_cache: Mutex::new(HashMap::new()),
-                       retry_attempts,
+                       retry,
                }
        }
 
@@ -292,7 +359,7 @@ where
                let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
                match self.payment_cache.lock().unwrap().entry(payment_hash) {
                        hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
-                       hash_map::Entry::Vacant(entry) => entry.insert(0),
+                       hash_map::Entry::Vacant(entry) => entry.insert(PaymentAttempts::new()),
                };
 
                let payment_secret = Some(invoice.payment_secret().clone());
@@ -311,6 +378,7 @@ where
                let send_payment = |route: &Route| {
                        self.payer.send_payment(route, payment_hash, &payment_secret)
                };
+
                self.pay_internal(&route_params, payment_hash, send_payment)
                        .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
        }
@@ -327,7 +395,7 @@ where
                let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
                match self.payment_cache.lock().unwrap().entry(payment_hash) {
                        hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
-                       hash_map::Entry::Vacant(entry) => entry.insert(0),
+                       hash_map::Entry::Vacant(entry) => entry.insert(PaymentAttempts::new()),
                };
 
                let route_params = RouteParameters {
@@ -367,13 +435,13 @@ where
                                PaymentSendFailure::PathParameterError(_) => Err(e),
                                PaymentSendFailure::AllFailedRetrySafe(_) => {
                                        let mut payment_cache = self.payment_cache.lock().unwrap();
-                                       let retry_count = payment_cache.get_mut(&payment_hash).unwrap();
-                                       if *retry_count >= self.retry_attempts.0 {
-                                               Err(e)
-                                       } else {
-                                               *retry_count += 1;
+                                       let payment_attempts = payment_cache.get_mut(&payment_hash).unwrap();
+                                       payment_attempts.count += 1;
+                                       if self.retry.is_retryable_now(payment_attempts) {
                                                core::mem::drop(payment_cache);
                                                Ok(self.pay_internal(params, payment_hash, send_payment)?)
+                                       } else {
+                                               Err(e)
                                        }
                                },
                                PaymentSendFailure::PartialFailure { failed_paths_retry, payment_id, .. } => {
@@ -399,20 +467,22 @@ where
        fn retry_payment(
                &self, payment_id: PaymentId, payment_hash: PaymentHash, params: &RouteParameters
        ) -> Result<(), ()> {
-               let max_payment_attempts = self.retry_attempts.0 + 1;
-               let attempts = *self.payment_cache.lock().unwrap()
-                       .entry(payment_hash)
-                       .and_modify(|attempts| *attempts += 1)
-                       .or_insert(1);
-
-               if attempts >= max_payment_attempts {
-                       log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
+               let attempts =
+                       *self.payment_cache.lock().unwrap().entry(payment_hash)
+                       .and_modify(|attempts| attempts.count += 1)
+                       .or_insert(PaymentAttempts {
+                               count: 1,
+                               first_attempted_at: T::now()
+                       });
+
+               if !self.retry.is_retryable_now(&attempts) {
+                       log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying ({})", log_bytes!(payment_hash.0), attempts);
                        return Err(());
                }
 
                #[cfg(feature = "std")] {
                        if has_expired(params) {
-                               log_trace!(self.logger, "Invoice expired for payment {}; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
+                               log_trace!(self.logger, "Invoice expired for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
                                return Err(());
                        }
                }
@@ -424,7 +494,7 @@ where
                        &self.scorer.lock()
                );
                if route.is_err() {
-                       log_trace!(self.logger, "Failed to find a route for payment {}; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
+                       log_trace!(self.logger, "Failed to find a route for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
                        return Err(());
                }
 
@@ -468,7 +538,7 @@ fn has_expired(route_params: &RouteParameters) -> bool {
        } else { false }
 }
 
-impl<P: Deref, R, S: Deref, L: Deref, E: EventHandler> EventHandler for InvoicePayer<P, R, S, L, E>
+impl<P: Deref, R, S: Deref, L: Deref, E: EventHandler, T: Time> EventHandler for InvoicePayerUsingTime<P, R, S, L, E, T>
 where
        P::Target: Payer,
        R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
@@ -511,7 +581,7 @@ where
                                let mut payment_cache = self.payment_cache.lock().unwrap();
                                let attempts = payment_cache
                                        .remove(payment_hash)
-                                       .map_or(1, |attempts| attempts + 1);
+                                       .map_or(1, |attempts| attempts.count + 1);
                                log_trace!(self.logger, "Payment {} succeeded (attempts: {})", log_bytes!(payment_hash.0), attempts);
                        },
                        _ => {},
@@ -541,6 +611,7 @@ mod tests {
        use std::cell::RefCell;
        use std::collections::VecDeque;
        use std::time::{SystemTime, Duration};
+       use time_utils::tests::SinceEpoch;
        use DEFAULT_EXPIRY_TIME;
 
        fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
@@ -624,7 +695,7 @@ mod tests {
                let scorer = RefCell::new(TestScorer::new());
                let logger = TestLogger::new();
                let invoice_payer =
-                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
+                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
 
                let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
                assert_eq!(*payer.attempts.borrow(), 1);
@@ -653,7 +724,7 @@ mod tests {
                let scorer = RefCell::new(TestScorer::new());
                let logger = TestLogger::new();
                let invoice_payer =
-                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
+                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
 
                let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
                assert_eq!(*payer.attempts.borrow(), 1);
@@ -698,7 +769,7 @@ mod tests {
                let scorer = RefCell::new(TestScorer::new());
                let logger = TestLogger::new();
                let invoice_payer =
-                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
+                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
 
                assert!(invoice_payer.pay_invoice(&invoice).is_ok());
        }
@@ -720,7 +791,7 @@ mod tests {
                let scorer = RefCell::new(TestScorer::new());
                let logger = TestLogger::new();
                let invoice_payer =
-                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
+                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
 
                let payment_id = Some(PaymentId([1; 32]));
                let event = Event::PaymentPathFailed {
@@ -749,7 +820,7 @@ mod tests {
        }
 
        #[test]
-       fn fails_paying_invoice_after_max_retries() {
+       fn fails_paying_invoice_after_max_retry_counts() {
                let event_handled = core::cell::RefCell::new(false);
                let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
 
@@ -765,7 +836,7 @@ mod tests {
                let scorer = RefCell::new(TestScorer::new());
                let logger = TestLogger::new();
                let invoice_payer =
-                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
+                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
 
                let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
                assert_eq!(*payer.attempts.borrow(), 1);
@@ -805,6 +876,52 @@ mod tests {
                assert_eq!(*payer.attempts.borrow(), 3);
        }
 
+       #[cfg(feature = "std")]
+       #[test]
+       fn fails_paying_invoice_after_max_retry_timeout() {
+               let event_handled = core::cell::RefCell::new(false);
+               let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
+
+               let payment_preimage = PaymentPreimage([1; 32]);
+               let invoice = invoice(payment_preimage);
+               let final_value_msat = invoice.amount_milli_satoshis().unwrap();
+
+               let payer = TestPayer::new()
+                       .expect_send(Amount::ForInvoice(final_value_msat))
+                       .expect_send(Amount::OnRetry(final_value_msat / 2));
+
+               let router = TestRouter {};
+               let scorer = RefCell::new(TestScorer::new());
+               let logger = TestLogger::new();
+               type InvoicePayerUsingSinceEpoch <P, R, S, L, E> = InvoicePayerUsingTime::<P, R, S, L, E, SinceEpoch>;
+
+               let invoice_payer =
+                       InvoicePayerUsingSinceEpoch::new(&payer, router, &scorer, &logger, event_handler, Retry::Timeout(Duration::from_secs(120)));
+
+               let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
+               assert_eq!(*payer.attempts.borrow(), 1);
+
+               let event = Event::PaymentPathFailed {
+                       payment_id,
+                       payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
+                       network_update: None,
+                       rejected_by_dest: false,
+                       all_paths_failed: true,
+                       path: TestRouter::path_for_value(final_value_msat),
+                       short_channel_id: None,
+                       retry: Some(TestRouter::retry_for_invoice(&invoice)),
+               };
+               invoice_payer.handle_event(&event);
+               assert_eq!(*event_handled.borrow(), false);
+               assert_eq!(*payer.attempts.borrow(), 2);
+
+               SinceEpoch::advance(Duration::from_secs(121));
+
+               invoice_payer.handle_event(&event);
+               assert_eq!(*event_handled.borrow(), true);
+               assert_eq!(*payer.attempts.borrow(), 2);
+       }
+
        #[test]
        fn fails_paying_invoice_with_missing_retry_params() {
                let event_handled = core::cell::RefCell::new(false);
@@ -819,7 +936,7 @@ mod tests {
                let scorer = RefCell::new(TestScorer::new());
                let logger = TestLogger::new();
                let invoice_payer =
-                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
+                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
 
                let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
                assert_eq!(*payer.attempts.borrow(), 1);
@@ -851,7 +968,7 @@ mod tests {
                let scorer = RefCell::new(TestScorer::new());
                let logger = TestLogger::new();
                let invoice_payer =
-                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
+                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
 
                let payment_preimage = PaymentPreimage([1; 32]);
                let invoice = expired_invoice(payment_preimage);
@@ -876,7 +993,7 @@ mod tests {
                let scorer = RefCell::new(TestScorer::new());
                let logger = TestLogger::new();
                let invoice_payer =
-                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
+                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
 
                let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
                assert_eq!(*payer.attempts.borrow(), 1);
@@ -917,7 +1034,7 @@ mod tests {
                let scorer = RefCell::new(TestScorer::new());
                let logger = TestLogger::new();
                let invoice_payer =
-                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
+                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
 
                let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
                assert_eq!(*payer.attempts.borrow(), 1);
@@ -951,7 +1068,7 @@ mod tests {
                let scorer = RefCell::new(TestScorer::new());
                let logger = TestLogger::new();
                let invoice_payer =
-                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
+                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
 
                let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
                assert_eq!(*payer.attempts.borrow(), 1);
@@ -987,7 +1104,7 @@ mod tests {
                let scorer = RefCell::new(TestScorer::new());
                let logger = TestLogger::new();
                let invoice_payer =
-                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
+                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
 
                let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
 
@@ -1026,7 +1143,7 @@ mod tests {
                let scorer = RefCell::new(TestScorer::new());
                let logger = TestLogger::new();
                let invoice_payer =
-                       InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, RetryAttempts(0));
+                       InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, Retry::Attempts(0));
 
                let payment_preimage = PaymentPreimage([1; 32]);
                let invoice = invoice(payment_preimage);
@@ -1050,7 +1167,7 @@ mod tests {
                let scorer = RefCell::new(TestScorer::new());
                let logger = TestLogger::new();
                let invoice_payer =
-                       InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, RetryAttempts(0));
+                       InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, Retry::Attempts(0));
 
                match invoice_payer.pay_invoice(&invoice) {
                        Err(PaymentError::Sending(_)) => {},
@@ -1074,7 +1191,7 @@ mod tests {
                let scorer = RefCell::new(TestScorer::new());
                let logger = TestLogger::new();
                let invoice_payer =
-                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
+                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
 
                let payment_id =
                        Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
@@ -1097,7 +1214,7 @@ mod tests {
                let scorer = RefCell::new(TestScorer::new());
                let logger = TestLogger::new();
                let invoice_payer =
-                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
+                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
 
                let payment_preimage = PaymentPreimage([1; 32]);
                let invoice = invoice(payment_preimage);
@@ -1128,7 +1245,7 @@ mod tests {
                let scorer = RefCell::new(TestScorer::new());
                let logger = TestLogger::new();
                let invoice_payer =
-                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
+                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
 
                let payment_id = Some(invoice_payer.pay_pubkey(
                                pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
@@ -1183,7 +1300,7 @@ mod tests {
                }));
                let logger = TestLogger::new();
                let invoice_payer =
-                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
+                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
 
                let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
                let event = Event::PaymentPathFailed {
@@ -1219,7 +1336,7 @@ mod tests {
                );
                let logger = TestLogger::new();
                let invoice_payer =
-                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
+                       InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
 
                let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
                let event = Event::PaymentPathSuccessful {
@@ -1554,7 +1671,7 @@ mod tests {
 
                let event_handler = |_: &_| { panic!(); };
                let scorer = RefCell::new(TestScorer::new());
-               let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, RetryAttempts(1));
+               let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, Retry::Attempts(1));
 
                assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
                        &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
@@ -1600,7 +1717,7 @@ mod tests {
 
                let event_handler = |_: &_| { panic!(); };
                let scorer = RefCell::new(TestScorer::new());
-               let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, RetryAttempts(1));
+               let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, Retry::Attempts(1));
 
                assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
                        &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
@@ -1682,7 +1799,7 @@ mod tests {
                        event_checker(event);
                };
                let scorer = RefCell::new(TestScorer::new());
-               let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, RetryAttempts(1));
+               let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, Retry::Attempts(1));
 
                assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
                        &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
diff --git a/lightning-invoice/src/time_utils.rs b/lightning-invoice/src/time_utils.rs
new file mode 120000 (symlink)
index 0000000..5326cff
--- /dev/null
@@ -0,0 +1 @@
+../../lightning/src/util/time.rs
\ No newline at end of file
index da6dc67aba5c4f52ec9e9dcd819aebf131d33084..4e85ae37d70125f3e4cb49a2723c4828f5efdad1 100644 (file)
@@ -80,7 +80,6 @@ enum NoiseState {
 }
 
 pub struct PeerChannelEncryptor {
-       secp_ctx: Secp256k1<secp256k1::SignOnly>,
        their_node_id: Option<PublicKey>, // filled in for outbound, or inbound after noise_state is Finished
 
        noise_state: NoiseState,
@@ -88,8 +87,6 @@ pub struct PeerChannelEncryptor {
 
 impl PeerChannelEncryptor {
        pub fn new_outbound(their_node_id: PublicKey, ephemeral_key: SecretKey) -> PeerChannelEncryptor {
-               let secp_ctx = Secp256k1::signing_only();
-
                let mut sha = Sha256::engine();
                sha.input(&NOISE_H);
                sha.input(&their_node_id.serialize()[..]);
@@ -97,7 +94,6 @@ impl PeerChannelEncryptor {
 
                PeerChannelEncryptor {
                        their_node_id: Some(their_node_id),
-                       secp_ctx,
                        noise_state: NoiseState::InProgress {
                                state: NoiseStep::PreActOne,
                                directional_state: DirectionalNoiseState::Outbound {
@@ -111,9 +107,7 @@ impl PeerChannelEncryptor {
                }
        }
 
-       pub fn new_inbound(our_node_secret: &SecretKey) -> PeerChannelEncryptor {
-               let secp_ctx = Secp256k1::signing_only();
-
+       pub fn new_inbound<C: secp256k1::Signing>(our_node_secret: &SecretKey, secp_ctx: &Secp256k1<C>) -> PeerChannelEncryptor {
                let mut sha = Sha256::engine();
                sha.input(&NOISE_H);
                let our_node_id = PublicKey::from_secret_key(&secp_ctx, our_node_secret);
@@ -122,7 +116,6 @@ impl PeerChannelEncryptor {
 
                PeerChannelEncryptor {
                        their_node_id: None,
-                       secp_ctx,
                        noise_state: NoiseState::InProgress {
                                state: NoiseStep::PreActOne,
                                directional_state: DirectionalNoiseState::Inbound {
@@ -224,7 +217,7 @@ impl PeerChannelEncryptor {
                Ok((their_pub, temp_k))
        }
 
-       pub fn get_act_one(&mut self) -> [u8; 50] {
+       pub fn get_act_one<C: secp256k1::Signing>(&mut self, secp_ctx: &Secp256k1<C>) -> [u8; 50] {
                match self.noise_state {
                        NoiseState::InProgress { ref mut state, ref directional_state, ref mut bidirectional_state } =>
                                match directional_state {
@@ -233,7 +226,7 @@ impl PeerChannelEncryptor {
                                                        panic!("Requested act at wrong step");
                                                }
 
-                                               let (res, _) = PeerChannelEncryptor::outbound_noise_act(&self.secp_ctx, bidirectional_state, &ie, &self.their_node_id.unwrap());
+                                               let (res, _) = PeerChannelEncryptor::outbound_noise_act(secp_ctx, bidirectional_state, &ie, &self.their_node_id.unwrap());
                                                *state = NoiseStep::PostActOne;
                                                res
                                        },
@@ -243,7 +236,9 @@ impl PeerChannelEncryptor {
                }
        }
 
-       pub fn process_act_one_with_keys(&mut self, act_one: &[u8], our_node_secret: &SecretKey, our_ephemeral: SecretKey) -> Result<[u8; 50], LightningError> {
+       pub fn process_act_one_with_keys<C: secp256k1::Signing>(
+               &mut self, act_one: &[u8], our_node_secret: &SecretKey, our_ephemeral: SecretKey, secp_ctx: &Secp256k1<C>)
+       -> Result<[u8; 50], LightningError> {
                assert_eq!(act_one.len(), 50);
 
                match self.noise_state {
@@ -259,7 +254,8 @@ impl PeerChannelEncryptor {
 
                                                re.get_or_insert(our_ephemeral);
 
-                                               let (res, temp_k) = PeerChannelEncryptor::outbound_noise_act(&self.secp_ctx, bidirectional_state, &re.unwrap(), &ie.unwrap());
+                                               let (res, temp_k) =
+                                                       PeerChannelEncryptor::outbound_noise_act(secp_ctx, bidirectional_state, &re.unwrap(), &ie.unwrap());
                                                *temp_k2 = Some(temp_k);
                                                *state = NoiseStep::PostActTwo;
                                                Ok(res)
@@ -270,7 +266,9 @@ impl PeerChannelEncryptor {
                }
        }
 
-       pub fn process_act_two(&mut self, act_two: &[u8], our_node_secret: &SecretKey) -> Result<([u8; 66], PublicKey), LightningError> {
+       pub fn process_act_two<C: secp256k1::Signing>(
+               &mut self, act_two: &[u8], our_node_secret: &SecretKey, secp_ctx: &Secp256k1<C>)
+       -> Result<([u8; 66], PublicKey), LightningError> {
                assert_eq!(act_two.len(), 50);
 
                let final_hkdf;
@@ -286,7 +284,7 @@ impl PeerChannelEncryptor {
                                                let (re, temp_k2) = PeerChannelEncryptor::inbound_noise_act(bidirectional_state, act_two, &ie)?;
 
                                                let mut res = [0; 66];
-                                               let our_node_id = PublicKey::from_secret_key(&self.secp_ctx, &our_node_secret);
+                                               let our_node_id = PublicKey::from_secret_key(secp_ctx, &our_node_secret);
 
                                                PeerChannelEncryptor::encrypt_with_ad(&mut res[1..50], 1, &temp_k2, &bidirectional_state.h, &our_node_id.serialize()[..]);
 
@@ -474,6 +472,7 @@ mod tests {
        use super::LN_MAX_MSG_LEN;
 
        use bitcoin::secp256k1::{PublicKey,SecretKey};
+       use bitcoin::secp256k1::Secp256k1;
 
        use hex;
 
@@ -481,9 +480,10 @@ mod tests {
 
        fn get_outbound_peer_for_initiator_test_vectors() -> PeerChannelEncryptor {
                let their_node_id = PublicKey::from_slice(&hex::decode("028d7500dd4c12685d1f568b4c2b5048e8534b873319f3a8daa612b469132ec7f7").unwrap()[..]).unwrap();
+               let secp_ctx = Secp256k1::signing_only();
 
                let mut outbound_peer = PeerChannelEncryptor::new_outbound(their_node_id, SecretKey::from_slice(&hex::decode("1212121212121212121212121212121212121212121212121212121212121212").unwrap()[..]).unwrap());
-               assert_eq!(outbound_peer.get_act_one()[..], hex::decode("00036360e856310ce5d294e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f70df6086551151f58b8afe6c195782c6a").unwrap()[..]);
+               assert_eq!(outbound_peer.get_act_one(&secp_ctx)[..], hex::decode("00036360e856310ce5d294e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f70df6086551151f58b8afe6c195782c6a").unwrap()[..]);
                outbound_peer
        }
 
@@ -491,11 +491,12 @@ mod tests {
                // transport-responder successful handshake
                let our_node_id = SecretKey::from_slice(&hex::decode("2121212121212121212121212121212121212121212121212121212121212121").unwrap()[..]).unwrap();
                let our_ephemeral = SecretKey::from_slice(&hex::decode("2222222222222222222222222222222222222222222222222222222222222222").unwrap()[..]).unwrap();
+               let secp_ctx = Secp256k1::signing_only();
 
-               let mut inbound_peer = PeerChannelEncryptor::new_inbound(&our_node_id);
+               let mut inbound_peer = PeerChannelEncryptor::new_inbound(&our_node_id, &secp_ctx);
 
                let act_one = hex::decode("00036360e856310ce5d294e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f70df6086551151f58b8afe6c195782c6a").unwrap().to_vec();
-               assert_eq!(inbound_peer.process_act_one_with_keys(&act_one[..], &our_node_id, our_ephemeral.clone()).unwrap()[..], hex::decode("0002466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae").unwrap()[..]);
+               assert_eq!(inbound_peer.process_act_one_with_keys(&act_one[..], &our_node_id, our_ephemeral.clone(), &secp_ctx).unwrap()[..], hex::decode("0002466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae").unwrap()[..]);
 
                let act_three = hex::decode("00b9e3a702e93e3a9948c2ed6e5fd7590a6e1c3a0344cfc9d5b57357049aa22355361aa02e55a8fc28fef5bd6d71ad0c38228dc68b1c466263b47fdf31e560e139ba").unwrap().to_vec();
                // test vector doesn't specify the initiator static key, but it's the same as the one
@@ -520,13 +521,14 @@ mod tests {
        #[test]
        fn noise_initiator_test_vectors() {
                let our_node_id = SecretKey::from_slice(&hex::decode("1111111111111111111111111111111111111111111111111111111111111111").unwrap()[..]).unwrap();
+               let secp_ctx = Secp256k1::signing_only();
 
                {
                        // transport-initiator successful handshake
                        let mut outbound_peer = get_outbound_peer_for_initiator_test_vectors();
 
                        let act_two = hex::decode("0002466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae").unwrap().to_vec();
-                       assert_eq!(outbound_peer.process_act_two(&act_two[..], &our_node_id).unwrap().0[..], hex::decode("00b9e3a702e93e3a9948c2ed6e5fd7590a6e1c3a0344cfc9d5b57357049aa22355361aa02e55a8fc28fef5bd6d71ad0c38228dc68b1c466263b47fdf31e560e139ba").unwrap()[..]);
+                       assert_eq!(outbound_peer.process_act_two(&act_two[..], &our_node_id, &secp_ctx).unwrap().0[..], hex::decode("00b9e3a702e93e3a9948c2ed6e5fd7590a6e1c3a0344cfc9d5b57357049aa22355361aa02e55a8fc28fef5bd6d71ad0c38228dc68b1c466263b47fdf31e560e139ba").unwrap()[..]);
 
                        match outbound_peer.noise_state {
                                NoiseState::Finished { sk, sn, sck, rk, rn, rck } => {
@@ -549,7 +551,7 @@ mod tests {
                        let mut outbound_peer = get_outbound_peer_for_initiator_test_vectors();
 
                        let act_two = hex::decode("0102466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae").unwrap().to_vec();
-                       assert!(outbound_peer.process_act_two(&act_two[..], &our_node_id).is_err());
+                       assert!(outbound_peer.process_act_two(&act_two[..], &our_node_id, &secp_ctx).is_err());
                }
 
                {
@@ -557,7 +559,7 @@ mod tests {
                        let mut outbound_peer = get_outbound_peer_for_initiator_test_vectors();
 
                        let act_two = hex::decode("0004466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae").unwrap().to_vec();
-                       assert!(outbound_peer.process_act_two(&act_two[..], &our_node_id).is_err());
+                       assert!(outbound_peer.process_act_two(&act_two[..], &our_node_id, &secp_ctx).is_err());
                }
 
                {
@@ -565,7 +567,7 @@ mod tests {
                        let mut outbound_peer = get_outbound_peer_for_initiator_test_vectors();
 
                        let act_two = hex::decode("0002466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730af").unwrap().to_vec();
-                       assert!(outbound_peer.process_act_two(&act_two[..], &our_node_id).is_err());
+                       assert!(outbound_peer.process_act_two(&act_two[..], &our_node_id, &secp_ctx).is_err());
                }
        }
 
@@ -573,6 +575,7 @@ mod tests {
        fn noise_responder_test_vectors() {
                let our_node_id = SecretKey::from_slice(&hex::decode("2121212121212121212121212121212121212121212121212121212121212121").unwrap()[..]).unwrap();
                let our_ephemeral = SecretKey::from_slice(&hex::decode("2222222222222222222222222222222222222222222222222222222222222222").unwrap()[..]).unwrap();
+               let secp_ctx = Secp256k1::signing_only();
 
                {
                        let _ = get_inbound_peer_for_test_vectors();
@@ -583,31 +586,31 @@ mod tests {
                }
                {
                        // transport-responder act1 bad version test
-                       let mut inbound_peer = PeerChannelEncryptor::new_inbound(&our_node_id);
+                       let mut inbound_peer = PeerChannelEncryptor::new_inbound(&our_node_id, &secp_ctx);
 
                        let act_one = hex::decode("01036360e856310ce5d294e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f70df6086551151f58b8afe6c195782c6a").unwrap().to_vec();
-                       assert!(inbound_peer.process_act_one_with_keys(&act_one[..], &our_node_id, our_ephemeral.clone()).is_err());
+                       assert!(inbound_peer.process_act_one_with_keys(&act_one[..], &our_node_id, our_ephemeral.clone(), &secp_ctx).is_err());
                }
                {
                        // transport-responder act1 bad key serialization test
-                       let mut inbound_peer = PeerChannelEncryptor::new_inbound(&our_node_id);
+                       let mut inbound_peer = PeerChannelEncryptor::new_inbound(&our_node_id, &secp_ctx);
 
                        let act_one =hex::decode("00046360e856310ce5d294e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f70df6086551151f58b8afe6c195782c6a").unwrap().to_vec();
-                       assert!(inbound_peer.process_act_one_with_keys(&act_one[..], &our_node_id, our_ephemeral.clone()).is_err());
+                       assert!(inbound_peer.process_act_one_with_keys(&act_one[..], &our_node_id, our_ephemeral.clone(), &secp_ctx).is_err());
                }
                {
                        // transport-responder act1 bad MAC test
-                       let mut inbound_peer = PeerChannelEncryptor::new_inbound(&our_node_id);
+                       let mut inbound_peer = PeerChannelEncryptor::new_inbound(&our_node_id, &secp_ctx);
 
                        let act_one = hex::decode("00036360e856310ce5d294e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f70df6086551151f58b8afe6c195782c6b").unwrap().to_vec();
-                       assert!(inbound_peer.process_act_one_with_keys(&act_one[..], &our_node_id, our_ephemeral.clone()).is_err());
+                       assert!(inbound_peer.process_act_one_with_keys(&act_one[..], &our_node_id, our_ephemeral.clone(), &secp_ctx).is_err());
                }
                {
                        // transport-responder act3 bad version test
-                       let mut inbound_peer = PeerChannelEncryptor::new_inbound(&our_node_id);
+                       let mut inbound_peer = PeerChannelEncryptor::new_inbound(&our_node_id, &secp_ctx);
 
                        let act_one = hex::decode("00036360e856310ce5d294e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f70df6086551151f58b8afe6c195782c6a").unwrap().to_vec();
-                       assert_eq!(inbound_peer.process_act_one_with_keys(&act_one[..], &our_node_id, our_ephemeral.clone()).unwrap()[..], hex::decode("0002466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae").unwrap()[..]);
+                       assert_eq!(inbound_peer.process_act_one_with_keys(&act_one[..], &our_node_id, our_ephemeral.clone(), &secp_ctx).unwrap()[..], hex::decode("0002466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae").unwrap()[..]);
 
                        let act_three = hex::decode("01b9e3a702e93e3a9948c2ed6e5fd7590a6e1c3a0344cfc9d5b57357049aa22355361aa02e55a8fc28fef5bd6d71ad0c38228dc68b1c466263b47fdf31e560e139ba").unwrap().to_vec();
                        assert!(inbound_peer.process_act_three(&act_three[..]).is_err());
@@ -618,30 +621,30 @@ mod tests {
                }
                {
                        // transport-responder act3 bad MAC for ciphertext test
-                       let mut inbound_peer = PeerChannelEncryptor::new_inbound(&our_node_id);
+                       let mut inbound_peer = PeerChannelEncryptor::new_inbound(&our_node_id, &secp_ctx);
 
                        let act_one = hex::decode("00036360e856310ce5d294e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f70df6086551151f58b8afe6c195782c6a").unwrap().to_vec();
-                       assert_eq!(inbound_peer.process_act_one_with_keys(&act_one[..], &our_node_id, our_ephemeral.clone()).unwrap()[..], hex::decode("0002466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae").unwrap()[..]);
+                       assert_eq!(inbound_peer.process_act_one_with_keys(&act_one[..], &our_node_id, our_ephemeral.clone(), &secp_ctx).unwrap()[..], hex::decode("0002466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae").unwrap()[..]);
 
                        let act_three = hex::decode("00c9e3a702e93e3a9948c2ed6e5fd7590a6e1c3a0344cfc9d5b57357049aa22355361aa02e55a8fc28fef5bd6d71ad0c38228dc68b1c466263b47fdf31e560e139ba").unwrap().to_vec();
                        assert!(inbound_peer.process_act_three(&act_three[..]).is_err());
                }
                {
                        // transport-responder act3 bad rs test
-                       let mut inbound_peer = PeerChannelEncryptor::new_inbound(&our_node_id);
+                       let mut inbound_peer = PeerChannelEncryptor::new_inbound(&our_node_id, &secp_ctx);
 
                        let act_one = hex::decode("00036360e856310ce5d294e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f70df6086551151f58b8afe6c195782c6a").unwrap().to_vec();
-                       assert_eq!(inbound_peer.process_act_one_with_keys(&act_one[..], &our_node_id, our_ephemeral.clone()).unwrap()[..], hex::decode("0002466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae").unwrap()[..]);
+                       assert_eq!(inbound_peer.process_act_one_with_keys(&act_one[..], &our_node_id, our_ephemeral.clone(), &secp_ctx).unwrap()[..], hex::decode("0002466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae").unwrap()[..]);
 
                        let act_three = hex::decode("00bfe3a702e93e3a9948c2ed6e5fd7590a6e1c3a0344cfc9d5b57357049aa2235536ad09a8ee351870c2bb7f78b754a26c6cef79a98d25139c856d7efd252c2ae73c").unwrap().to_vec();
                        assert!(inbound_peer.process_act_three(&act_three[..]).is_err());
                }
                {
                        // transport-responder act3 bad MAC test
-                       let mut inbound_peer = PeerChannelEncryptor::new_inbound(&our_node_id);
+                       let mut inbound_peer = PeerChannelEncryptor::new_inbound(&our_node_id, &secp_ctx);
 
                        let act_one = hex::decode("00036360e856310ce5d294e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f70df6086551151f58b8afe6c195782c6a").unwrap().to_vec();
-                       assert_eq!(inbound_peer.process_act_one_with_keys(&act_one[..], &our_node_id, our_ephemeral.clone()).unwrap()[..], hex::decode("0002466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae").unwrap()[..]);
+                       assert_eq!(inbound_peer.process_act_one_with_keys(&act_one[..], &our_node_id, our_ephemeral.clone(), &secp_ctx).unwrap()[..], hex::decode("0002466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae").unwrap()[..]);
 
                        let act_three = hex::decode("00b9e3a702e93e3a9948c2ed6e5fd7590a6e1c3a0344cfc9d5b57357049aa22355361aa02e55a8fc28fef5bd6d71ad0c38228dc68b1c466263b47fdf31e560e139bb").unwrap().to_vec();
                        assert!(inbound_peer.process_act_three(&act_three[..]).is_err());
@@ -654,12 +657,13 @@ mod tests {
                // We use the same keys as the initiator and responder test vectors, so we copy those tests
                // here and use them to encrypt.
                let mut outbound_peer = get_outbound_peer_for_initiator_test_vectors();
+               let secp_ctx = Secp256k1::signing_only();
 
                {
                        let our_node_id = SecretKey::from_slice(&hex::decode("1111111111111111111111111111111111111111111111111111111111111111").unwrap()[..]).unwrap();
 
                        let act_two = hex::decode("0002466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae").unwrap().to_vec();
-                       assert_eq!(outbound_peer.process_act_two(&act_two[..], &our_node_id).unwrap().0[..], hex::decode("00b9e3a702e93e3a9948c2ed6e5fd7590a6e1c3a0344cfc9d5b57357049aa22355361aa02e55a8fc28fef5bd6d71ad0c38228dc68b1c466263b47fdf31e560e139ba").unwrap()[..]);
+                       assert_eq!(outbound_peer.process_act_two(&act_two[..], &our_node_id, &secp_ctx).unwrap().0[..], hex::decode("00b9e3a702e93e3a9948c2ed6e5fd7590a6e1c3a0344cfc9d5b57357049aa22355361aa02e55a8fc28fef5bd6d71ad0c38228dc68b1c466263b47fdf31e560e139ba").unwrap()[..]);
 
                        match outbound_peer.noise_state {
                                NoiseState::Finished { sk, sn, sck, rk, rn, rck } => {
index 4b777b0b99446e0d4781e6029592b60ee0e24ff7..f128f6c5259802466cf99f27496b554d7b88f9ea 100644 (file)
@@ -15,7 +15,7 @@
 //! call into the provided message handlers (probably a ChannelManager and NetGraphmsgHandler) with messages
 //! they should handle, and encoding/sending response messages.
 
-use bitcoin::secp256k1::{SecretKey,PublicKey};
+use bitcoin::secp256k1::{self, Secp256k1, SecretKey, PublicKey};
 
 use ln::features::InitFeatures;
 use ln::msgs;
@@ -455,6 +455,7 @@ pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: De
        peer_counter: AtomicCounter,
 
        logger: L,
+       secp_ctx: Secp256k1<secp256k1::SignOnly>
 }
 
 enum MessageHandlingError {
@@ -573,6 +574,10 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref, CMH: Deref> P
                let mut ephemeral_key_midstate = Sha256::engine();
                ephemeral_key_midstate.input(ephemeral_random_data);
 
+               let mut secp_ctx = Secp256k1::signing_only();
+               let ephemeral_hash = Sha256::from_engine(ephemeral_key_midstate.clone()).into_inner();
+               secp_ctx.seeded_randomize(&ephemeral_hash);
+
                PeerManager {
                        message_handler,
                        peers: FairRwLock::new(HashMap::new()),
@@ -584,6 +589,7 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref, CMH: Deref> P
                        peer_counter: AtomicCounter::new(),
                        logger,
                        custom_message_handler,
+                       secp_ctx,
                }
        }
 
@@ -628,7 +634,7 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref, CMH: Deref> P
        /// [`socket_disconnected()`]: PeerManager::socket_disconnected
        pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor, remote_network_address: Option<NetAddress>) -> Result<Vec<u8>, PeerHandleError> {
                let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
-               let res = peer_encryptor.get_act_one().to_vec();
+               let res = peer_encryptor.get_act_one(&self.secp_ctx).to_vec();
                let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
 
                let mut peers = self.peers.write().unwrap();
@@ -675,7 +681,7 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref, CMH: Deref> P
        ///
        /// [`socket_disconnected()`]: PeerManager::socket_disconnected
        pub fn new_inbound_connection(&self, descriptor: Descriptor, remote_network_address: Option<NetAddress>) -> Result<(), PeerHandleError> {
-               let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret);
+               let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret, &self.secp_ctx);
                let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
 
                let mut peers = self.peers.write().unwrap();
@@ -940,14 +946,16 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref, CMH: Deref> P
                                                let next_step = peer.channel_encryptor.get_noise_step();
                                                match next_step {
                                                        NextNoiseStep::ActOne => {
-                                                               let act_two = try_potential_handleerror!(peer,
-                                                                       peer.channel_encryptor.process_act_one_with_keys(&peer.pending_read_buffer[..], &self.our_node_secret, self.get_ephemeral_key())).to_vec();
+                                                               let act_two = try_potential_handleerror!(peer, peer.channel_encryptor
+                                                                       .process_act_one_with_keys(&peer.pending_read_buffer[..],
+                                                                               &self.our_node_secret, self.get_ephemeral_key(), &self.secp_ctx)).to_vec();
                                                                peer.pending_outbound_buffer.push_back(act_two);
                                                                peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
                                                        },
                                                        NextNoiseStep::ActTwo => {
                                                                let (act_three, their_node_id) = try_potential_handleerror!(peer,
-                                                                       peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..], &self.our_node_secret));
+                                                                       peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..],
+                                                                               &self.our_node_secret, &self.secp_ctx));
                                                                peer.pending_outbound_buffer.push_back(act_three.to_vec());
                                                                peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
                                                                peer.pending_read_is_header = true;
index 4c47aac47b64c2e78df2b39d0e740083023ecadc..cffd2d90533b7290250b5a4886ad8c55fa5462fd 100644 (file)
@@ -59,6 +59,7 @@ use routing::network_graph::{NetworkGraph, NodeId};
 use routing::router::RouteHop;
 use util::ser::{Readable, ReadableArgs, Writeable, Writer};
 use util::logger::Logger;
+use util::time::Time;
 
 use prelude::*;
 use core::fmt;
@@ -262,7 +263,9 @@ pub type Scorer = ScorerUsingTime::<ConfiguredTime>;
 #[cfg(not(feature = "no-std"))]
 type ConfiguredTime = std::time::Instant;
 #[cfg(feature = "no-std")]
-type ConfiguredTime = time::Eternity;
+use util::time::Eternity;
+#[cfg(feature = "no-std")]
+type ConfiguredTime = Eternity;
 
 // Note that ideally we'd hide ScorerUsingTime from public view by sealing it as well, but rustdoc
 // doesn't handle this well - instead exposing a `Scorer` which has no trait implementation(s) or
@@ -1327,83 +1330,11 @@ impl<T: Time> Readable for ChannelLiquidity<T> {
        }
 }
 
-pub(crate) mod time {
-       use core::ops::Sub;
-       use core::time::Duration;
-       /// A measurement of time.
-       pub trait Time: Copy + Sub<Duration, Output = Self> where Self: Sized {
-               /// Returns an instance corresponding to the current moment.
-               fn now() -> Self;
-
-               /// Returns the amount of time elapsed since `self` was created.
-               fn elapsed(&self) -> Duration;
-
-               /// Returns the amount of time passed between `earlier` and `self`.
-               fn duration_since(&self, earlier: Self) -> Duration;
-
-               /// Returns the amount of time passed since the beginning of [`Time`].
-               ///
-               /// Used during (de-)serialization.
-               fn duration_since_epoch() -> Duration;
-       }
-
-       /// A state in which time has no meaning.
-       #[derive(Clone, Copy, Debug, PartialEq, Eq)]
-       pub struct Eternity;
-
-       #[cfg(not(feature = "no-std"))]
-       impl Time for std::time::Instant {
-               fn now() -> Self {
-                       std::time::Instant::now()
-               }
-
-               fn duration_since(&self, earlier: Self) -> Duration {
-                       self.duration_since(earlier)
-               }
-
-               fn duration_since_epoch() -> Duration {
-                       use std::time::SystemTime;
-                       SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap()
-               }
-
-               fn elapsed(&self) -> Duration {
-                       std::time::Instant::elapsed(self)
-               }
-       }
-
-       impl Time for Eternity {
-               fn now() -> Self {
-                       Self
-               }
-
-               fn duration_since(&self, _earlier: Self) -> Duration {
-                       Duration::from_secs(0)
-               }
-
-               fn duration_since_epoch() -> Duration {
-                       Duration::from_secs(0)
-               }
-
-               fn elapsed(&self) -> Duration {
-                       Duration::from_secs(0)
-               }
-       }
-
-       impl Sub<Duration> for Eternity {
-               type Output = Self;
-
-               fn sub(self, _other: Duration) -> Self {
-                       self
-               }
-       }
-}
-
-pub(crate) use self::time::Time;
-
 #[cfg(test)]
 mod tests {
-       use super::{ChannelLiquidity, ProbabilisticScoringParameters, ProbabilisticScorerUsingTime, ScoringParameters, ScorerUsingTime, Time};
-       use super::time::Eternity;
+       use super::{ChannelLiquidity, ProbabilisticScoringParameters, ProbabilisticScorerUsingTime, ScoringParameters, ScorerUsingTime};
+       use util::time::Time;
+       use util::time::tests::SinceEpoch;
 
        use ln::features::{ChannelFeatures, NodeFeatures};
        use ln::msgs::{ChannelAnnouncement, ChannelUpdate, OptionalField, UnsignedChannelAnnouncement, UnsignedChannelUpdate};
@@ -1418,80 +1349,9 @@ mod tests {
        use bitcoin::hashes::sha256d::Hash as Sha256dHash;
        use bitcoin::network::constants::Network;
        use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
-       use core::cell::Cell;
-       use core::ops::Sub;
        use core::time::Duration;
        use io;
 
-       // `Time` tests
-
-       /// Time that can be advanced manually in tests.
-       #[derive(Clone, Copy, Debug, PartialEq, Eq)]
-       struct SinceEpoch(Duration);
-
-       impl SinceEpoch {
-               thread_local! {
-                       static ELAPSED: Cell<Duration> = core::cell::Cell::new(Duration::from_secs(0));
-               }
-
-               fn advance(duration: Duration) {
-                       Self::ELAPSED.with(|elapsed| elapsed.set(elapsed.get() + duration))
-               }
-       }
-
-       impl Time for SinceEpoch {
-               fn now() -> Self {
-                       Self(Self::duration_since_epoch())
-               }
-
-               fn duration_since(&self, earlier: Self) -> Duration {
-                       self.0 - earlier.0
-               }
-
-               fn duration_since_epoch() -> Duration {
-                       Self::ELAPSED.with(|elapsed| elapsed.get())
-               }
-
-               fn elapsed(&self) -> Duration {
-                       Self::duration_since_epoch() - self.0
-               }
-       }
-
-       impl Sub<Duration> for SinceEpoch {
-               type Output = Self;
-
-               fn sub(self, other: Duration) -> Self {
-                       Self(self.0 - other)
-               }
-       }
-
-       #[test]
-       fn time_passes_when_advanced() {
-               let now = SinceEpoch::now();
-               assert_eq!(now.elapsed(), Duration::from_secs(0));
-
-               SinceEpoch::advance(Duration::from_secs(1));
-               SinceEpoch::advance(Duration::from_secs(1));
-
-               let elapsed = now.elapsed();
-               let later = SinceEpoch::now();
-
-               assert_eq!(elapsed, Duration::from_secs(2));
-               assert_eq!(later - elapsed, now);
-       }
-
-       #[test]
-       fn time_never_passes_in_an_eternity() {
-               let now = Eternity::now();
-               let elapsed = now.elapsed();
-               let later = Eternity::now();
-
-               assert_eq!(now.elapsed(), Duration::from_secs(0));
-               assert_eq!(later - elapsed, now);
-       }
-
-       // `Scorer` tests
-
        /// A scorer for testing with time that can be manually advanced.
        type Scorer = ScorerUsingTime::<SinceEpoch>;
 
index b7ee02d2c1f5724ba0b0b6309ce2eb35ad321c1d..c6181ab269a57a19a8d5ee8c9f225358d6695947 100644 (file)
@@ -36,6 +36,7 @@ pub(crate) mod poly1305;
 pub(crate) mod chacha20poly1305rfc;
 pub(crate) mod transaction_utils;
 pub(crate) mod scid_utils;
+pub(crate) mod time;
 
 /// Logging macro utilities.
 #[macro_use]
diff --git a/lightning/src/util/time.rs b/lightning/src/util/time.rs
new file mode 100644 (file)
index 0000000..d3768aa
--- /dev/null
@@ -0,0 +1,152 @@
+// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
+// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
+// You may not use this file except in accordance with one or both of these
+// licenses.
+
+//! [`Time`] trait and different implementations. Currently, it's mainly used in tests so we can
+//! manually advance time.
+//! Other crates may symlink this file to use it while [`Time`] trait is sealed here.
+
+use core::ops::Sub;
+use core::time::Duration;
+
+/// A measurement of time.
+pub trait Time: Copy + Sub<Duration, Output = Self> where Self: Sized {
+       /// Returns an instance corresponding to the current moment.
+       fn now() -> Self;
+
+       /// Returns the amount of time elapsed since `self` was created.
+       fn elapsed(&self) -> Duration;
+
+       /// Returns the amount of time passed between `earlier` and `self`.
+       fn duration_since(&self, earlier: Self) -> Duration;
+
+       /// Returns the amount of time passed since the beginning of [`Time`].
+       ///
+       /// Used during (de-)serialization.
+       fn duration_since_epoch() -> Duration;
+}
+
+/// A state in which time has no meaning.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Eternity;
+
+impl Time for Eternity {
+       fn now() -> Self {
+               Self
+       }
+
+       fn duration_since(&self, _earlier: Self) -> Duration {
+               Duration::from_secs(0)
+       }
+
+       fn duration_since_epoch() -> Duration {
+               Duration::from_secs(0)
+       }
+
+       fn elapsed(&self) -> Duration {
+               Duration::from_secs(0)
+       }
+}
+
+impl Sub<Duration> for Eternity {
+       type Output = Self;
+
+       fn sub(self, _other: Duration) -> Self {
+               self
+       }
+}
+
+#[cfg(not(feature = "no-std"))]
+impl Time for std::time::Instant {
+       fn now() -> Self {
+               std::time::Instant::now()
+       }
+
+       fn duration_since(&self, earlier: Self) -> Duration {
+               self.duration_since(earlier)
+       }
+
+       fn duration_since_epoch() -> Duration {
+               use std::time::SystemTime;
+               SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap()
+       }
+       fn elapsed(&self) -> Duration {
+               std::time::Instant::elapsed(self)
+       }
+}
+
+#[cfg(test)]
+pub mod tests {
+       use super::{Time, Eternity};
+
+       use core::time::Duration;
+       use core::ops::Sub;
+       use core::cell::Cell;
+
+       /// Time that can be advanced manually in tests.
+       #[derive(Clone, Copy, Debug, PartialEq, Eq)]
+       pub struct SinceEpoch(Duration);
+
+       impl SinceEpoch {
+               thread_local! {
+                       static ELAPSED: Cell<Duration> = core::cell::Cell::new(Duration::from_secs(0));
+               }
+
+               pub fn advance(duration: Duration) {
+                       Self::ELAPSED.with(|elapsed| elapsed.set(elapsed.get() + duration))
+               }
+       }
+
+       impl Time for SinceEpoch {
+               fn now() -> Self {
+                       Self(Self::duration_since_epoch())
+               }
+
+               fn duration_since(&self, earlier: Self) -> Duration {
+                       self.0 - earlier.0
+               }
+
+               fn duration_since_epoch() -> Duration {
+                       Self::ELAPSED.with(|elapsed| elapsed.get())
+               }
+
+               fn elapsed(&self) -> Duration {
+                       Self::duration_since_epoch() - self.0
+               }
+       }
+
+       impl Sub<Duration> for SinceEpoch {
+               type Output = Self;
+
+               fn sub(self, other: Duration) -> Self {
+                       Self(self.0 - other)
+               }
+       }
+
+       #[test]
+       fn time_passes_when_advanced() {
+               let now = SinceEpoch::now();
+               assert_eq!(now.elapsed(), Duration::from_secs(0));
+
+               SinceEpoch::advance(Duration::from_secs(1));
+               SinceEpoch::advance(Duration::from_secs(1));
+
+               let elapsed = now.elapsed();
+               let later = SinceEpoch::now();
+
+               assert_eq!(elapsed, Duration::from_secs(2));
+               assert_eq!(later - elapsed, now);
+       }
+
+       #[test]
+       fn time_never_passes_in_an_eternity() {
+               let now = Eternity::now();
+               let elapsed = now.elapsed();
+               let later = Eternity::now();
+
+               assert_eq!(now.elapsed(), Duration::from_secs(0));
+               assert_eq!(later - elapsed, now);
+       }
+}