Consider maximum path length during path finding.
use lightning::ln::peer_channel_encryptor::PeerChannelEncryptor;
-use bitcoin::secp256k1::{PublicKey,SecretKey};
+use bitcoin::secp256k1::{Secp256k1, PublicKey, SecretKey};
use utils::test_logger;
}
}
+ let secp_ctx = Secp256k1::signing_only();
+
let our_network_key = match SecretKey::from_slice(get_slice!(32)) {
Ok(key) => key,
Err(_) => return,
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,
}
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;
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());
pub mod payment;
pub mod utils;
+pub(crate) mod time_utils;
+
extern crate bech32;
extern crate bitcoin_hashes;
#[macro_use] extern crate lightning;
//! # 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>() {
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")]
/// 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>,
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.
) -> 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)]
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>,
/// 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,
logger,
event_handler,
payment_cache: Mutex::new(HashMap::new()),
- retry_attempts,
+ retry,
}
}
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());
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 })
}
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 {
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, .. } => {
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(());
}
}
&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(());
}
} 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>,
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);
},
_ => {},
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 {
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);
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);
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());
}
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 {
}
#[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; };
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);
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);
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);
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);
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);
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);
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);
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());
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);
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(_)) => {},
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());
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);
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
}));
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 {
);
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 {
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(),
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(),
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(),
--- /dev/null
+../../lightning/src/util/time.rs
\ No newline at end of file
}
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,
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()[..]);
PeerChannelEncryptor {
their_node_id: Some(their_node_id),
- secp_ctx,
noise_state: NoiseState::InProgress {
state: NoiseStep::PreActOne,
directional_state: DirectionalNoiseState::Outbound {
}
}
- 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);
PeerChannelEncryptor {
their_node_id: None,
- secp_ctx,
noise_state: NoiseState::InProgress {
state: NoiseStep::PreActOne,
directional_state: DirectionalNoiseState::Inbound {
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 {
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
},
}
}
- 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 {
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)
}
}
- 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;
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()[..]);
use super::LN_MAX_MSG_LEN;
use bitcoin::secp256k1::{PublicKey,SecretKey};
+ use bitcoin::secp256k1::Secp256k1;
use hex;
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
}
// 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
#[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 } => {
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());
}
{
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());
}
{
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());
}
}
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();
}
{
// 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());
}
{
// 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());
// 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 } => {
//! 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;
peer_counter: AtomicCounter,
logger: L,
+ secp_ctx: Secp256k1<secp256k1::SignOnly>
}
enum MessageHandlingError {
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()),
peer_counter: AtomicCounter::new(),
logger,
custom_message_handler,
+ secp_ctx,
}
}
/// [`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();
///
/// [`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();
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;
use routing::router::RouteHop;
use util::ser::{Readable, ReadableArgs, Writeable, Writer};
use util::logger::Logger;
+use util::time::Time;
use prelude::*;
use core::fmt;
#[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
}
}
-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};
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>;
pub(crate) mod chacha20poly1305rfc;
pub(crate) mod transaction_utils;
pub(crate) mod scid_utils;
+pub(crate) mod time;
/// Logging macro utilities.
#[macro_use]
--- /dev/null
+// 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);
+ }
+}