})
}
- fn create_blinded_payment_paths<
- ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification
- >(
+ fn create_blinded_payment_paths<T: secp256k1::Signing + secp256k1::Verification>(
&self, _recipient: PublicKey, _first_hops: Vec<ChannelDetails>, _tlvs: ReceiveTlvs,
- _amount_msats: u64, _entropy_source: &ES, _secp_ctx: &Secp256k1<T>
+ _amount_msats: u64, _secp_ctx: &Secp256k1<T>,
) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()> {
unreachable!()
}
unreachable!()
}
- fn create_blinded_paths<
- ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification
- >(
- &self, _recipient: PublicKey, _peers: Vec<PublicKey>, _entropy_source: &ES,
- _secp_ctx: &Secp256k1<T>
+ fn create_blinded_paths<T: secp256k1::Signing + secp256k1::Verification>(
+ &self, _recipient: PublicKey, _peers: Vec<PublicKey>, _secp_ctx: &Secp256k1<T>,
) -> Result<Vec<BlindedPath>, ()> {
unreachable!()
}
})
}
- fn create_blinded_payment_paths<
- ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification
- >(
+ fn create_blinded_payment_paths<T: secp256k1::Signing + secp256k1::Verification>(
&self, _recipient: PublicKey, _first_hops: Vec<ChannelDetails>, _tlvs: ReceiveTlvs,
- _amount_msats: u64, _entropy_source: &ES, _secp_ctx: &Secp256k1<T>
+ _amount_msats: u64, _secp_ctx: &Secp256k1<T>,
) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()> {
unreachable!()
}
unreachable!()
}
- fn create_blinded_paths<
- ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification
- >(
- &self, _recipient: PublicKey, _peers: Vec<PublicKey>, _entropy_source: &ES,
- _secp_ctx: &Secp256k1<T>
+ fn create_blinded_paths<T: secp256k1::Signing + secp256k1::Verification>(
+ &self, _recipient: PublicKey, _peers: Vec<PublicKey>, _secp_ctx: &Secp256k1<T>,
) -> Result<Vec<BlindedPath>, ()> {
unreachable!()
}
})
}
- fn create_blinded_paths<
- ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification
- >(
- &self, _recipient: PublicKey, _peers: Vec<PublicKey>, _entropy_source: &ES,
- _secp_ctx: &Secp256k1<T>
+ fn create_blinded_paths<T: secp256k1::Signing + secp256k1::Verification>(
+ &self, _recipient: PublicKey, _peers: Vec<PublicKey>, _secp_ctx: &Secp256k1<T>,
) -> Result<Vec<BlindedPath>, ()> {
unreachable!()
}
Arc<DefaultRouter<
Arc<NetworkGraph<Arc<test_utils::TestLogger>>>,
Arc<test_utils::TestLogger>,
+ Arc<KeysManager>,
Arc<LockingWrapper<TestScorer>>,
(),
TestScorer>
let genesis_block = genesis_block(network);
let network_graph = Arc::new(NetworkGraph::new(network, logger.clone()));
let scorer = Arc::new(LockingWrapper::new(TestScorer::new()));
+ let now = Duration::from_secs(genesis_block.header.time as u64);
let seed = [i as u8; 32];
- let router = Arc::new(DefaultRouter::new(network_graph.clone(), logger.clone(), seed, scorer.clone(), Default::default()));
+ let keys_manager = Arc::new(KeysManager::new(&seed, now.as_secs(), now.subsec_nanos()));
+ let router = Arc::new(DefaultRouter::new(network_graph.clone(), logger.clone(), Arc::clone(&keys_manager), scorer.clone(), Default::default()));
let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Bitcoin));
let kv_store = Arc::new(FilesystemStore::new(format!("{}_persister_{}", &persist_dir, i).into()));
- let now = Duration::from_secs(genesis_block.header.time as u64);
- let keys_manager = Arc::new(KeysManager::new(&seed, now.as_secs(), now.subsec_nanos()));
let chain_monitor = Arc::new(chainmonitor::ChainMonitor::new(Some(chain_source.clone()), tx_broadcaster.clone(), logger.clone(), fee_estimator.clone(), kv_store.clone()));
let best_block = BestBlock::from_network(network);
let params = ChainParameters { network, best_block };
+++ /dev/null
-use core::fmt::Debug;
-use core::fmt::Formatter;
-use lightning::ln::msgs::{DecodeError, LightningError};
-
-/// All-encompassing standard error type that processing can return
-pub enum GraphSyncError {
- /// Error trying to read the update data, typically due to an erroneous data length indication
- /// that is greater than the actual amount of data provided
- DecodeError(DecodeError),
- /// Error applying the patch to the network graph, usually the result of updates that are too
- /// old or missing prerequisite data to the application of updates out of order
- LightningError(LightningError),
-}
-
-impl From<lightning::io::Error> for GraphSyncError {
- fn from(error: lightning::io::Error) -> Self {
- Self::DecodeError(DecodeError::Io(error.kind()))
- }
-}
-
-impl From<DecodeError> for GraphSyncError {
- fn from(error: DecodeError) -> Self {
- Self::DecodeError(error)
- }
-}
-
-impl From<LightningError> for GraphSyncError {
- fn from(error: LightningError) -> Self {
- Self::LightningError(error)
- }
-}
-
-impl Debug for GraphSyncError {
- fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
- match self {
- GraphSyncError::DecodeError(e) => f.write_fmt(format_args!("DecodeError: {:?}", e)),
- GraphSyncError::LightningError(e) => f.write_fmt(format_args!("LightningError: {:?}", e))
- }
- }
-}
use core::sync::atomic::{AtomicBool, Ordering};
use lightning::io;
+use lightning::ln::msgs::{DecodeError, LightningError};
use lightning::routing::gossip::NetworkGraph;
use lightning::util::logger::Logger;
-pub use crate::error::GraphSyncError;
-
-/// Error types that these functions can return
-mod error;
-
/// Core functionality of this crate
mod processing;
+/// All-encompassing standard error type that processing can return
+#[derive(Debug)]
+pub enum GraphSyncError {
+ /// Error trying to read the update data, typically due to an erroneous data length indication
+ /// that is greater than the actual amount of data provided
+ DecodeError(DecodeError),
+ /// Error applying the patch to the network graph, usually the result of updates that are too
+ /// old or missing prerequisite data to the application of updates out of order
+ LightningError(LightningError),
+}
+
+impl From<lightning::io::Error> for GraphSyncError {
+ fn from(error: lightning::io::Error) -> Self {
+ Self::DecodeError(DecodeError::Io(error.kind()))
+ }
+}
+
+impl From<DecodeError> for GraphSyncError {
+ fn from(error: DecodeError) -> Self {
+ Self::DecodeError(error)
+ }
+}
+
+impl From<LightningError> for GraphSyncError {
+ fn from(error: LightningError) -> Self {
+ Self::LightningError(error)
+ }
+}
+
/// The main Rapid Gossip Sync object.
///
/// See [crate-level documentation] for usage.
use lightning::ln::msgs::DecodeError;
use lightning::routing::gossip::NetworkGraph;
use lightning::util::test_utils::TestLogger;
- use crate::RapidGossipSync;
+ use crate::{GraphSyncError, RapidGossipSync};
#[test]
fn test_sync_from_file() {
let start = std::time::Instant::now();
let sync_result = rapid_sync
.sync_network_graph_with_file_path("./res/full_graph.lngossip");
- if let Err(crate::error::GraphSyncError::DecodeError(DecodeError::Io(io_error))) = &sync_result {
+ if let Err(GraphSyncError::DecodeError(DecodeError::Io(io_error))) = &sync_result {
let error_string = format!("Input file lightning-rapid-gossip-sync/res/full_graph.lngossip is missing! Download it from https://bitcoin.ninja/ldk-compressed_graph-285cb27df79-2022-07-21.bin\n\n{:?}", io_error);
#[cfg(not(require_route_graph_test))]
{
use lightning::util::ser::{BigSize, Readable};
use lightning::io;
-use crate::error::GraphSyncError;
-use crate::RapidGossipSync;
+use crate::{GraphSyncError, RapidGossipSync};
#[cfg(all(feature = "std", not(test)))]
use std::time::{SystemTime, UNIX_EPOCH};
use lightning::routing::gossip::NetworkGraph;
use lightning::util::test_utils::TestLogger;
- use crate::error::GraphSyncError;
use crate::processing::STALE_RGS_UPDATE_AGE_LIMIT_SECS;
- use crate::RapidGossipSync;
+ use crate::{GraphSyncError, RapidGossipSync};
const VALID_RGS_BINARY: [u8; 300] = [
76, 68, 75, 1, 111, 226, 140, 10, 182, 241, 179, 114, 193, 166, 162, 70, 174, 99, 247,
let chan_upd_2_3 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).0.contents;
let chan_upd_3_4 = create_announced_chan_between_nodes_with_value(&nodes, 3, 4, 1_000_000, 0).0.contents;
+ // Get all our nodes onto the same height so payments don't fail for CLTV violations.
+ connect_blocks(&nodes[0], nodes[4].best_block_info().1 - nodes[0].best_block_info().1);
+ connect_blocks(&nodes[1], nodes[4].best_block_info().1 - nodes[1].best_block_info().1);
+ connect_blocks(&nodes[2], nodes[4].best_block_info().1 - nodes[2].best_block_info().1);
+ assert_eq!(nodes[4].best_block_info().1, nodes[3].best_block_info().1);
+
let amt_msat = 5000;
let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[4], Some(amt_msat), None);
let route_params = get_blinded_route_parameters(amt_msat, payment_secret,
Arc<DefaultRouter<
Arc<NetworkGraph<Arc<L>>>,
Arc<L>,
+ Arc<KeysManager>,
Arc<RwLock<ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>>>,
ProbabilisticScoringFeeParameters,
ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>,
&'e DefaultRouter<
&'f NetworkGraph<&'g L>,
&'g L,
+ &'c KeysManager,
&'h RwLock<ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>>,
ProbabilisticScoringFeeParameters,
ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>
/// Errors if the `MessageRouter` errors or returns an empty `Vec`.
fn create_blinded_path(&self) -> Result<BlindedPath, ()> {
let recipient = self.get_our_node_id();
- let entropy_source = self.entropy_source.deref();
let secp_ctx = &self.secp_ctx;
let peers = self.per_peer_state.read().unwrap()
.collect::<Vec<_>>();
self.router
- .create_blinded_paths(recipient, peers, entropy_source, secp_ctx)
+ .create_blinded_paths(recipient, peers, secp_ctx)
.and_then(|paths| paths.into_iter().next().ok_or(()))
}
fn create_blinded_payment_paths(
&self, amount_msats: u64, payment_secret: PaymentSecret
) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()> {
- let entropy_source = self.entropy_source.deref();
let secp_ctx = &self.secp_ctx;
let first_hops = self.list_usable_channels();
},
};
self.router.create_blinded_payment_paths(
- payee_node_id, first_hops, payee_tlvs, amount_msats, entropy_source, secp_ctx
+ payee_node_id, first_hops, payee_tlvs, amount_msats, secp_ctx
)
}
tx_broadcaster: &chanmon_cfgs[i].tx_broadcaster,
fee_estimator: &chanmon_cfgs[i].fee_estimator,
router: test_utils::TestRouter::new(network_graph.clone(), &chanmon_cfgs[i].logger, &chanmon_cfgs[i].scorer),
- message_router: test_utils::TestMessageRouter::new(network_graph.clone()),
+ message_router: test_utils::TestMessageRouter::new(network_graph.clone(), &chanmon_cfgs[i].keys_manager),
chain_monitor,
keys_manager: &chanmon_cfgs[i].keys_manager,
node_seed: seed,
let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
let scorer = RwLock::new(test_utils::TestScorer::new());
let router = test_utils::TestRouter::new(network_graph.clone(), &chanmon_cfgs[0].logger, &scorer);
- let message_router = test_utils::TestMessageRouter::new(network_graph.clone());
+ let message_router = test_utils::TestMessageRouter::new(network_graph.clone(), &keys_manager);
let node = NodeCfg { chain_source: &chanmon_cfgs[0].chain_source, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, router, message_router, chain_monitor, keys_manager: &keys_manager, network_graph, node_seed: seed, override_init_features: alloc::rc::Rc::new(core::cell::RefCell::new(None)) };
let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
node_cfgs.remove(0);
use crate::events::{Event, EventsProvider};
use crate::ln::features::InitFeatures;
use crate::ln::msgs::{self, DecodeError, OnionMessageHandler, SocketAddress};
-use crate::sign::{EntropySource, NodeSigner, Recipient};
+use crate::sign::{NodeSigner, Recipient};
use crate::util::ser::{FixedLengthReader, LengthReadable, Writeable, Writer};
use crate::util::test_utils;
use super::messenger::{CustomOnionMessageHandler, Destination, MessageRouter, OnionMessagePath, OnionMessenger, PendingOnionMessage, SendError};
}
fn create_blinded_paths<
- ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification
+ T: secp256k1::Signing + secp256k1::Verification
>(
- &self, _recipient: PublicKey, _peers: Vec<PublicKey>, _entropy_source: &ES,
- _secp_ctx: &Secp256k1<T>
+ &self, _recipient: PublicKey, _peers: Vec<PublicKey>, _secp_ctx: &Secp256k1<T>,
) -> Result<Vec<BlindedPath>, ()> {
unreachable!()
}
/// # first_node_addresses: None,
/// # })
/// # }
-/// # fn create_blinded_paths<ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification>(
-/// # &self, _recipient: PublicKey, _peers: Vec<PublicKey>, _entropy_source: &ES, _secp_ctx: &Secp256k1<T>
+/// # fn create_blinded_paths<T: secp256k1::Signing + secp256k1::Verification>(
+/// # &self, _recipient: PublicKey, _peers: Vec<PublicKey>, _secp_ctx: &Secp256k1<T>
/// # ) -> Result<Vec<BlindedPath>, ()> {
/// # unreachable!()
/// # }
/// Creates [`BlindedPath`]s to the `recipient` node. The nodes in `peers` are assumed to be
/// direct peers with the `recipient`.
fn create_blinded_paths<
- ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification
+ T: secp256k1::Signing + secp256k1::Verification
>(
- &self, recipient: PublicKey, peers: Vec<PublicKey>, entropy_source: &ES,
- secp_ctx: &Secp256k1<T>
+ &self, recipient: PublicKey, peers: Vec<PublicKey>, secp_ctx: &Secp256k1<T>,
) -> Result<Vec<BlindedPath>, ()>;
}
/// A [`MessageRouter`] that can only route to a directly connected [`Destination`].
-pub struct DefaultMessageRouter<G: Deref<Target=NetworkGraph<L>>, L: Deref>
+pub struct DefaultMessageRouter<G: Deref<Target=NetworkGraph<L>>, L: Deref, ES: Deref>
where
L::Target: Logger,
+ ES::Target: EntropySource,
{
network_graph: G,
+ entropy_source: ES,
}
-impl<G: Deref<Target=NetworkGraph<L>>, L: Deref> DefaultMessageRouter<G, L>
+impl<G: Deref<Target=NetworkGraph<L>>, L: Deref, ES: Deref> DefaultMessageRouter<G, L, ES>
where
L::Target: Logger,
+ ES::Target: EntropySource,
{
/// Creates a [`DefaultMessageRouter`] using the given [`NetworkGraph`].
- pub fn new(network_graph: G) -> Self {
- Self { network_graph }
+ pub fn new(network_graph: G, entropy_source: ES) -> Self {
+ Self { network_graph, entropy_source }
}
}
-impl<G: Deref<Target=NetworkGraph<L>>, L: Deref> MessageRouter for DefaultMessageRouter<G, L>
+impl<G: Deref<Target=NetworkGraph<L>>, L: Deref, ES: Deref> MessageRouter for DefaultMessageRouter<G, L, ES>
where
L::Target: Logger,
+ ES::Target: EntropySource,
{
fn find_path(
&self, _sender: PublicKey, peers: Vec<PublicKey>, destination: Destination
}
fn create_blinded_paths<
- ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification
+ T: secp256k1::Signing + secp256k1::Verification
>(
- &self, recipient: PublicKey, peers: Vec<PublicKey>, entropy_source: &ES,
- secp_ctx: &Secp256k1<T>
+ &self, recipient: PublicKey, peers: Vec<PublicKey>, secp_ctx: &Secp256k1<T>,
) -> Result<Vec<BlindedPath>, ()> {
// Limit the number of blinded paths that are computed.
const MAX_PATHS: usize = 3;
.unwrap_or(false)
)
.map(|pubkey| vec![*pubkey, recipient])
- .map(|node_pks| BlindedPath::new_for_message(&node_pks, entropy_source, secp_ctx))
+ .map(|node_pks| BlindedPath::new_for_message(&node_pks, &*self.entropy_source, secp_ctx))
.take(MAX_PATHS)
.collect::<Result<Vec<_>, _>>();
Ok(paths) if !paths.is_empty() => Ok(paths),
_ => {
if network_graph.nodes().contains_key(&NodeId::from_pubkey(&recipient)) {
- BlindedPath::one_hop_for_message(recipient, entropy_source, secp_ctx)
+ BlindedPath::one_hop_for_message(recipient, &*self.entropy_source, secp_ctx)
.map(|path| vec![path])
} else {
Err(())
Arc<KeysManager>,
Arc<KeysManager>,
Arc<L>,
- Arc<DefaultMessageRouter<Arc<NetworkGraph<Arc<L>>>, Arc<L>>>,
+ Arc<DefaultMessageRouter<Arc<NetworkGraph<Arc<L>>>, Arc<L>, Arc<KeysManager>>>,
Arc<SimpleArcChannelManager<M, T, F, L>>,
IgnoringMessageHandler
>;
&'a KeysManager,
&'a KeysManager,
&'b L,
- &'i DefaultMessageRouter<&'g NetworkGraph<&'b L>, &'b L>,
+ &'i DefaultMessageRouter<&'g NetworkGraph<&'b L>, &'b L, &'a KeysManager>,
&'j SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L>,
IgnoringMessageHandler
>;
//! The router finds paths within a [`NetworkGraph`] for a payment.
use bitcoin::secp256k1::{PublicKey, Secp256k1, self};
-use bitcoin::hashes::Hash;
-use bitcoin::hashes::sha256::Hash as Sha256;
use crate::blinded_path::{BlindedHop, BlindedPath};
use crate::blinded_path::payment::{ForwardNode, ForwardTlvs, PaymentConstraints, PaymentRelay, ReceiveTlvs};
use crate::io;
use crate::prelude::*;
-use crate::sync::Mutex;
use alloc::collections::BinaryHeap;
use core::{cmp, fmt};
use core::ops::Deref;
/// A [`Router`] implemented using [`find_route`].
-pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> where
+pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, ES: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> where
L::Target: Logger,
S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
+ ES::Target: EntropySource,
{
network_graph: G,
logger: L,
- random_seed_bytes: Mutex<[u8; 32]>,
+ entropy_source: ES,
scorer: S,
score_params: SP,
- message_router: DefaultMessageRouter<G, L>,
+ message_router: DefaultMessageRouter<G, L, ES>,
}
-impl<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> DefaultRouter<G, L, S, SP, Sc> where
+impl<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, ES: Deref + Clone, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> DefaultRouter<G, L, ES, S, SP, Sc> where
L::Target: Logger,
S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
+ ES::Target: EntropySource,
{
/// Creates a new router.
- pub fn new(network_graph: G, logger: L, random_seed_bytes: [u8; 32], scorer: S, score_params: SP) -> Self {
- let random_seed_bytes = Mutex::new(random_seed_bytes);
- let message_router = DefaultMessageRouter::new(network_graph.clone());
- Self { network_graph, logger, random_seed_bytes, scorer, score_params, message_router }
+ pub fn new(network_graph: G, logger: L, entropy_source: ES, scorer: S, score_params: SP) -> Self {
+ let message_router = DefaultMessageRouter::new(network_graph.clone(), entropy_source.clone());
+ Self { network_graph, logger, entropy_source, scorer, score_params, message_router }
}
}
-impl<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> Router for DefaultRouter<G, L, S, SP, Sc> where
+impl<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, ES: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> Router for DefaultRouter<G, L, ES, S, SP, Sc> where
L::Target: Logger,
S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
+ ES::Target: EntropySource,
{
fn find_route(
&self,
first_hops: Option<&[&ChannelDetails]>,
inflight_htlcs: InFlightHtlcs
) -> Result<Route, LightningError> {
- let random_seed_bytes = {
- let mut locked_random_seed_bytes = self.random_seed_bytes.lock().unwrap();
- *locked_random_seed_bytes = Sha256::hash(&*locked_random_seed_bytes).to_byte_array();
- *locked_random_seed_bytes
- };
+ let random_seed_bytes = self.entropy_source.get_secure_random_bytes();
find_route(
payer, params, &self.network_graph, first_hops, &*self.logger,
&ScorerAccountingForInFlightHtlcs::new(self.scorer.read_lock(), &inflight_htlcs),
}
fn create_blinded_payment_paths<
- ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification
- >(
+ T: secp256k1::Signing + secp256k1::Verification
+ > (
&self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
- amount_msats: u64, entropy_source: &ES, secp_ctx: &Secp256k1<T>
+ amount_msats: u64, secp_ctx: &Secp256k1<T>
) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()> {
// Limit the number of blinded paths that are computed.
const MAX_PAYMENT_PATHS: usize = 3;
})
.map(|forward_node| {
BlindedPath::new_for_payment(
- &[forward_node], recipient, tlvs.clone(), u64::MAX, entropy_source, secp_ctx
+ &[forward_node], recipient, tlvs.clone(), u64::MAX, &*self.entropy_source, secp_ctx
)
})
.take(MAX_PAYMENT_PATHS)
Ok(paths) if !paths.is_empty() => Ok(paths),
_ => {
if network_graph.nodes().contains_key(&NodeId::from_pubkey(&recipient)) {
- BlindedPath::one_hop_for_payment(recipient, tlvs, entropy_source, secp_ctx)
+ BlindedPath::one_hop_for_payment(recipient, tlvs, &*self.entropy_source, secp_ctx)
.map(|path| vec![path])
} else {
Err(())
}
}
-impl< G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> MessageRouter for DefaultRouter<G, L, S, SP, Sc> where
+impl< G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, ES: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> MessageRouter for DefaultRouter<G, L, ES, S, SP, Sc> where
L::Target: Logger,
S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
+ ES::Target: EntropySource,
{
fn find_path(
&self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination
}
fn create_blinded_paths<
- ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification
- >(
- &self, recipient: PublicKey, peers: Vec<PublicKey>, entropy_source: &ES,
- secp_ctx: &Secp256k1<T>
+ T: secp256k1::Signing + secp256k1::Verification
+ > (
+ &self, recipient: PublicKey, peers: Vec<PublicKey>, secp_ctx: &Secp256k1<T>,
) -> Result<Vec<BlindedPath>, ()> {
- self.message_router.create_blinded_paths(recipient, peers, entropy_source, secp_ctx)
+ self.message_router.create_blinded_paths(recipient, peers, secp_ctx)
}
}
/// are assumed to be with the `recipient`'s peers. The payment secret and any constraints are
/// given in `tlvs`.
fn create_blinded_payment_paths<
- ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification
- >(
+ T: secp256k1::Signing + secp256k1::Verification
+ > (
&self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
- amount_msats: u64, entropy_source: &ES, secp_ctx: &Secp256k1<T>
+ amount_msats: u64, secp_ctx: &Secp256k1<T>
) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()>;
}
/// has been funded and is able to pay), and accessor methods may panic otherwise.
///
/// [`find_route`] validates this prior to constructing a [`CandidateRouteHop`].
+ ///
+ /// This is not exported to bindings users as lifetimes are not expressable in most languages.
pub details: &'a ChannelDetails,
/// The node id of the payer, which is also the source side of this candidate route hop.
+ ///
+ /// This is not exported to bindings users as lifetimes are not expressable in most languages.
pub payer_node_id: &'a NodeId,
}
pub struct PublicHopCandidate<'a> {
/// Information about the channel, including potentially its capacity and
/// direction-specific information.
+ ///
+ /// This is not exported to bindings users as lifetimes are not expressable in most languages.
pub info: DirectedChannelInfo<'a>,
/// The short channel ID of the channel, i.e. the identifier by which we refer to this
/// channel.
#[derive(Clone, Debug)]
pub struct PrivateHopCandidate<'a> {
/// Information about the private hop communicated via BOLT 11.
+ ///
+ /// This is not exported to bindings users as lifetimes are not expressable in most languages.
pub hint: &'a RouteHintHop,
/// Node id of the next hop in BOLT 11 route hint.
+ ///
+ /// This is not exported to bindings users as lifetimes are not expressable in most languages.
pub target_node_id: &'a NodeId
}
pub struct BlindedPathCandidate<'a> {
/// Information about the blinded path including the fee, HTLC amount limits, and
/// cryptographic material required to build an HTLC through the given path.
+ ///
+ /// This is not exported to bindings users as lifetimes are not expressable in most languages.
pub hint: &'a (BlindedPayInfo, BlindedPath),
/// Index of the hint in the original list of blinded hints.
///
/// cryptographic material required to build an HTLC terminating with the given path.
///
/// Note that the [`BlindedPayInfo`] is ignored here.
+ ///
+ /// This is not exported to bindings users as lifetimes are not expressable in most languages.
pub hint: &'a (BlindedPayInfo, BlindedPath),
/// Index of the hint in the original list of blinded hints.
///
}
}
+macro_rules! impl_record {
+ ($($args: lifetime)?, $($nonstruct_args: lifetime)?) => {
/// A Record, unit of logging output with Metadata to enable filtering
/// Module_path, file, line to inform on log's source
#[derive(Clone, Debug)]
-pub struct Record<'a> {
+pub struct Record<$($args)?> {
/// The verbosity level of the message.
pub level: Level,
/// The node id of the peer pertaining to the logged record.
pub file: &'static str,
/// The line containing the message.
pub line: u32,
-
- #[cfg(c_bindings)]
- /// We don't actually use the lifetime parameter in C bindings (as there is no good way to
- /// communicate a lifetime to a C, or worse, Java user).
- _phantom: core::marker::PhantomData<&'a ()>,
}
-impl<'a> Record<'a> {
+impl<$($args)?> Record<$($args)?> {
/// Returns a new Record.
///
/// This is not exported to bindings users as fmt can't be used in C
#[inline]
- pub fn new(
+ pub fn new<$($nonstruct_args)?>(
level: Level, peer_id: Option<PublicKey>, channel_id: Option<ChannelId>,
args: fmt::Arguments<'a>, module_path: &'static str, file: &'static str, line: u32
- ) -> Record<'a> {
+ ) -> Record<$($args)?> {
Record {
level,
peer_id,
module_path,
file,
line,
- #[cfg(c_bindings)]
- _phantom: core::marker::PhantomData,
}
}
}
+} }
+#[cfg(not(c_bindings))]
+impl_record!('a, );
+#[cfg(c_bindings)]
+impl_record!(, 'a);
/// A trait encapsulating the operations required of a logger.
pub trait Logger {
}
/// Adds relevant context to a [`Record`] before passing it to the wrapped [`Logger`].
+///
+/// This is not exported to bindings users as lifetimes are problematic and there's little reason
+/// for this to be used downstream anyway.
pub struct WithContext<'a, L: Deref> where L::Target: Logger {
/// The logger to delegate to after adding context to the record.
logger: &'a L,
use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use core::mem;
use bitcoin::bech32::u5;
-use crate::sign::{InMemorySigner, Recipient, EntropySource, NodeSigner, SignerProvider};
+use crate::sign::{InMemorySigner, RandomBytes, Recipient, EntropySource, NodeSigner, SignerProvider};
#[cfg(feature = "std")]
use std::time::{SystemTime, UNIX_EPOCH};
pub router: DefaultRouter<
Arc<NetworkGraph<&'a TestLogger>>,
&'a TestLogger,
+ Arc<RandomBytes>,
&'a RwLock<TestScorer>,
(),
TestScorer,
>,
+ //pub entropy_source: &'a RandomBytes,
pub network_graph: Arc<NetworkGraph<&'a TestLogger>>,
pub next_routes: Mutex<VecDeque<(RouteParameters, Result<Route, LightningError>)>>,
pub scorer: &'a RwLock<TestScorer>,
impl<'a> TestRouter<'a> {
pub fn new(
network_graph: Arc<NetworkGraph<&'a TestLogger>>, logger: &'a TestLogger,
- scorer: &'a RwLock<TestScorer>
+ scorer: &'a RwLock<TestScorer>,
) -> Self {
+ let entropy_source = Arc::new(RandomBytes::new([42; 32]));
Self {
- router: DefaultRouter::new(network_graph.clone(), logger, [42u8; 32], scorer, ()),
+ router: DefaultRouter::new(network_graph.clone(), logger, entropy_source, scorer, ()),
network_graph,
next_routes: Mutex::new(VecDeque::new()),
scorer,
details: first_hops[idx],
payer_node_id: &node_id,
});
- scorer.channel_penalty_msat(&candidate, usage, &());
+ scorer.channel_penalty_msat(&candidate, usage, &Default::default());
continue;
}
}
info: directed,
short_channel_id: hop.short_channel_id,
});
- scorer.channel_penalty_msat(&candidate, usage, &());
+ scorer.channel_penalty_msat(&candidate, usage, &Default::default());
} else {
let target_node_id = NodeId::from_pubkey(&hop.pubkey);
let route_hint = RouteHintHop {
hint: &route_hint,
target_node_id: &target_node_id,
});
- scorer.channel_penalty_msat(&candidate, usage, &());
+ scorer.channel_penalty_msat(&candidate, usage, &Default::default());
}
prev_hop_node = &hop.pubkey;
}
}
fn create_blinded_payment_paths<
- ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification
+ T: secp256k1::Signing + secp256k1::Verification
>(
&self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
- amount_msats: u64, entropy_source: &ES, secp_ctx: &Secp256k1<T>
+ amount_msats: u64, secp_ctx: &Secp256k1<T>,
) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()> {
self.router.create_blinded_payment_paths(
- recipient, first_hops, tlvs, amount_msats, entropy_source, secp_ctx
+ recipient, first_hops, tlvs, amount_msats, secp_ctx
)
}
}
}
fn create_blinded_paths<
- ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification
+ T: secp256k1::Signing + secp256k1::Verification
>(
- &self, recipient: PublicKey, peers: Vec<PublicKey>, entropy_source: &ES,
- secp_ctx: &Secp256k1<T>
+ &self, recipient: PublicKey, peers: Vec<PublicKey>, secp_ctx: &Secp256k1<T>,
) -> Result<Vec<BlindedPath>, ()> {
- self.router.create_blinded_paths(recipient, peers, entropy_source, secp_ctx)
+ self.router.create_blinded_paths(recipient, peers, secp_ctx)
}
}
}
pub struct TestMessageRouter<'a> {
- inner: DefaultMessageRouter<Arc<NetworkGraph<&'a TestLogger>>, &'a TestLogger>,
+ inner: DefaultMessageRouter<Arc<NetworkGraph<&'a TestLogger>>, &'a TestLogger, &'a TestKeysInterface>,
}
impl<'a> TestMessageRouter<'a> {
- pub fn new(network_graph: Arc<NetworkGraph<&'a TestLogger>>) -> Self {
- Self { inner: DefaultMessageRouter::new(network_graph) }
+ pub fn new(network_graph: Arc<NetworkGraph<&'a TestLogger>>, entropy_source: &'a TestKeysInterface) -> Self {
+ Self { inner: DefaultMessageRouter::new(network_graph, entropy_source) }
}
}
self.inner.find_path(sender, peers, destination)
}
- fn create_blinded_paths<
- ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification
- >(
- &self, recipient: PublicKey, peers: Vec<PublicKey>, entropy_source: &ES,
- secp_ctx: &Secp256k1<T>
+ fn create_blinded_paths<T: secp256k1::Signing + secp256k1::Verification>(
+ &self, recipient: PublicKey, peers: Vec<PublicKey>, secp_ctx: &Secp256k1<T>,
) -> Result<Vec<BlindedPath>, ()> {
- self.inner.create_blinded_paths(recipient, peers, entropy_source, secp_ctx)
+ self.inner.create_blinded_paths(recipient, peers, secp_ctx)
}
}