Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions bindings/ldk_node.udl
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,6 +13,8 @@ typedef dictionary TorConfig;

typedef interface NodeEntropy;

typedef interface ProbingConfig;

typedef enum WordCount;

[Remote]
Expand All@@ -32,6 +34,18 @@ interface LogWriter {
void log(LogRecord record);
};

interface ProbingConfigBuilder {
[Name=high_degree]
constructor(u64 top_node_count);
[Name=random_walk]
constructor(u64 max_hops);
void set_interval(u64 secs);
void set_max_locked_msat(u64 max_msat);
void set_diversity_penalty_msat(u64 penalty_msat);
void set_cooldown(u64 secs);
ProbingConfig build();
};

interface Builder {
constructor();
[Name=from_config]
Expand DownExpand Up@@ -59,6 +73,7 @@ interface Builder {
void set_node_alias(string node_alias);
[Throws=BuildError]
void set_async_payments_role(AsyncPaymentsRole? role);
void set_probing_config(ProbingConfig config);
[Throws=BuildError]
Node build(NodeEntropy node_entropy);
[Throws=BuildError]
Expand Down
93 changes: 91 additions & 2 deletions src/builder.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -50,6 +50,7 @@ use crate::config::{
default_user_config, may_announce_channel, AnnounceError, AsyncPaymentsRole,
BitcoindRestClientConfig, Config, ElectrumSyncConfig, EsploraSyncConfig, HRNResolverConfig,
TorConfig, DEFAULT_ESPLORA_SERVER_URL, DEFAULT_LOG_FILENAME, DEFAULT_LOG_LEVEL,
DEFAULT_MAX_PROBE_AMOUNT_MSAT, DEFAULT_MIN_PROBE_AMOUNT_MSAT,
};
use crate::connection::ConnectionManager;
use crate::entropy::NodeEntropy;
Expand All@@ -74,6 +75,10 @@ use crate::logger::{log_error, LdkLogger, LogLevel, LogWriter, Logger};
use crate::message_handler::NodeCustomMessageHandler;
use crate::payment::asynchronous::om_mailbox::OnionMessageMailbox;
use crate::peer_store::PeerStore;
use crate::probing::{
HighDegreeStrategy, Prober, ProbingConfig, ProbingStrategy, ProbingStrategyKind,
RandomWalkStrategy,
};
use crate::runtime::{Runtime, RuntimeSpawner};
use crate::tx_broadcaster::TransactionBroadcaster;
use crate::types::{
Expand DownExpand Up@@ -306,6 +311,7 @@ pub struct NodeBuilder {
async_payments_role: Option<AsyncPaymentsRole>,
runtime_handle: Option<tokio::runtime::Handle>,
pathfinding_scores_sync_config: Option<PathfindingScoresSyncConfig>,
probing_config: Option<ProbingConfig>,
}

impl NodeBuilder {
Expand All@@ -323,6 +329,7 @@ impl NodeBuilder {
let log_writer_config = None;
let runtime_handle = None;
let pathfinding_scores_sync_config = None;
let probing_config = None;
Self {
config,
chain_data_source_config,
Expand All@@ -332,6 +339,7 @@ impl NodeBuilder {
runtime_handle,
async_payments_role: None,
pathfinding_scores_sync_config,
probing_config,
}
}

Expand DownExpand Up@@ -629,6 +637,31 @@ impl NodeBuilder {
Ok(self)
}

/// Sets background probing config.
///
/// Use [`ProbingConfigBuilder`] to build the configuration:
/// ```no_run
/// # #[cfg(not(feature = "uniffi"))]
/// # {
/// use std::time::Duration;
/// use ldk_node::Builder;
/// use ldk_node::probing::ProbingConfigBuilder;
///
/// let mut builder = Builder::new();
/// builder.set_probing_config(
/// ProbingConfigBuilder::high_degree(100)
/// .interval(Duration::from_secs(30))
/// .build()
/// );
/// # }
/// ```
///
/// [`ProbingConfigBuilder`]: crate::probing::ProbingConfigBuilder
pub fn set_probing_config(&mut self, config: ProbingConfig) -> &mut Self {
self.probing_config = Some(config);
self
}

/// Builds a [`Node`] instance with a [`SqliteStore`] backend and according to the options
/// previously configured.
pub fn build(&self, node_entropy: NodeEntropy) -> Result<Node, BuildError> {
Expand DownExpand Up@@ -868,6 +901,7 @@ impl NodeBuilder {
self.gossip_source_config.as_ref(),
self.liquidity_source_config.as_ref(),
self.pathfinding_scores_sync_config.as_ref(),
self.probing_config.as_ref(),
self.async_payments_role,
seed_bytes,
runtime,
Expand DownExpand Up@@ -1166,6 +1200,15 @@ impl ArcedNodeBuilder {
self.inner.write().expect("lock").set_async_payments_role(role).map(|_| ())
}

/// Configures background probing.
///
/// Use [`ProbingConfigBuilder`] to build the configuration.
///
/// [`ProbingConfigBuilder`]: crate::probing::ProbingConfigBuilder
pub fn set_probing_config(&self, config: Arc<ProbingConfig>) {
self.inner.write().expect("lock").set_probing_config((*config).clone());
}

/// Builds a [`Node`] instance with a [`SqliteStore`] backend and according to the options
/// previously configured.
pub fn build(&self, node_entropy: Arc<NodeEntropy>) -> Result<Arc<Node>, BuildError> {
Expand DownExpand Up@@ -1361,8 +1404,8 @@ fn build_with_store_internal(
gossip_source_config: Option<&GossipSourceConfig>,
liquidity_source_config: Option<&LiquiditySourceConfig>,
pathfinding_scores_sync_config: Option<&PathfindingScoresSyncConfig>,
async_payments_role: Option<AsyncPaymentsRole>, seed_bytes: [u8; 64], runtime: Arc<Runtime>,
logger: Arc<Logger>, kv_store: Arc<DynStore>,
probing_config: Option<&ProbingConfig>, async_payments_role: Option<AsyncPaymentsRole>,
seed_bytes: [u8; 64], runtime: Arc<Runtime>, logger: Arc<Logger>, kv_store: Arc<DynStore>,
) -> Result<Node, BuildError> {
optionally_install_rustls_cryptoprovider();

Expand DownExpand Up@@ -2219,6 +2262,51 @@ fn build_with_store_internal(
_leak_checker.0.push(Arc::downgrade(&wallet) as Weak<dyn Any + Send + Sync>);
}

let prober = probing_config.map(|probing_cfg| {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Would be better to move this up before the leak checker setup.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

moved

let strategy: Arc<dyn ProbingStrategy> = match &probing_cfg.kind {
ProbingStrategyKind::HighDegree { top_node_count } => {
// Dedicated router for probing so the diversity penalty doesn't interfere
// with real payments; shares the scorer so probe results still train it.
let mut probing_fee_params = ProbabilisticScoringFeeParameters::default();
Comment thread
randomlogin marked this conversation as resolved.
if let Some(penalty) = probing_cfg.diversity_penalty_msat {
probing_fee_params.probing_diversity_penalty_msat = penalty;
}
let probing_router = Arc::new(DefaultRouter::new(
Arc::clone(&network_graph),
Arc::clone(&logger),
Arc::clone(&keys_manager),
Arc::clone(&scorer),
probing_fee_params,
));
Arc::new(HighDegreeStrategy::new(
Arc::clone(&network_graph),
Arc::clone(&channel_manager),
probing_router,
*top_node_count,
DEFAULT_MIN_PROBE_AMOUNT_MSAT,
DEFAULT_MAX_PROBE_AMOUNT_MSAT,
probing_cfg.cooldown,
config.probing_liquidity_limit_multiplier,
))
},
ProbingStrategyKind::RandomWalk { max_hops } => Arc::new(RandomWalkStrategy::new(
Arc::clone(&network_graph),
Arc::clone(&channel_manager),
*max_hops,
DEFAULT_MIN_PROBE_AMOUNT_MSAT,
DEFAULT_MAX_PROBE_AMOUNT_MSAT,
)),
ProbingStrategyKind::Custom(s) => Arc::clone(s),
};
Arc::new(Prober {
channel_manager: Arc::clone(&channel_manager),
logger: Arc::clone(&logger),
strategy,
interval: probing_cfg.interval,
max_locked_msat: probing_cfg.max_locked_msat,
})
});

Ok(Node {
runtime,
stop_sender,
Expand DownExpand Up@@ -2252,6 +2340,7 @@ fn build_with_store_internal(
om_mailbox,
async_payments_role,
hrn_resolver,
prober,
#[cfg(cycle_tests)]
_leak_checker,
})
Expand Down
6 changes: 6 additions & 0 deletions src/config.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,6 +28,12 @@ const DEFAULT_BDK_WALLET_SYNC_INTERVAL_SECS: u64 = 80;
const DEFAULT_LDK_WALLET_SYNC_INTERVAL_SECS: u64 = 30;
const DEFAULT_FEE_RATE_CACHE_UPDATE_INTERVAL_SECS: u64 = 60 * 10;
const DEFAULT_PROBING_LIQUIDITY_LIMIT_MULTIPLIER: u64 = 3;
pub(crate) const DEFAULT_PROBING_INTERVAL_SECS: u64 = 10;
pub(crate) const MIN_PROBING_INTERVAL: Duration = Duration::from_millis(100);
pub(crate) const DEFAULT_PROBED_NODE_COOLDOWN_SECS: u64 = 60 * 60; // 1 hour
pub(crate) const DEFAULT_MAX_PROBE_LOCKED_MSAT: u64 = 100_000_000; // 100k sats
pub(crate) const DEFAULT_MIN_PROBE_AMOUNT_MSAT: u64 = 1_000_000; // 1k sats
pub(crate) const DEFAULT_MAX_PROBE_AMOUNT_MSAT: u64 = 10_000_000; // 10k sats
const DEFAULT_ANCHOR_PER_CHANNEL_RESERVE_SATS: u64 = 25_000;

// The default timeout after which we abort a wallet syncing operation.
Expand Down
31 changes: 21 additions & 10 deletions src/event.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -52,6 +52,7 @@ use crate::payment::store::{
PaymentDetails, PaymentDetailsUpdate, PaymentDirection, PaymentKind, PaymentStatus,
};
use crate::payment::PaymentMetadata;
use crate::probing::Prober;
use crate::runtime::Runtime;
use crate::types::{
CustomTlvRecord, DynStore, KeysManager, OnionMessenger, PaymentStore, Sweeper, Wallet,
Expand DownExpand Up@@ -536,12 +537,13 @@ where
payment_store: Arc<PaymentStore>,
peer_store: Arc<PeerStore<L>>,
keys_manager: Arc<KeysManager>,
runtime: Arc<Runtime>,
logger: L,
config: Arc<Config>,
static_invoice_store: Option<StaticInvoiceStore>,
onion_messenger: Arc<OnionMessenger>,
om_mailbox: Option<Arc<OnionMessageMailbox>>,
prober: Option<Arc<Prober>>,
runtime: Arc<Runtime>,
logger: L,
config: Arc<Config>,
}

impl<L: Deref + Clone + Sync + Send + 'static> EventHandler<L>
Expand All@@ -556,8 +558,8 @@ where
liquidity_source: Arc<LiquiditySource<Arc<Logger>>>, payment_store: Arc<PaymentStore>,
peer_store: Arc<PeerStore<L>>, keys_manager: Arc<KeysManager>,
static_invoice_store: Option<StaticInvoiceStore>, onion_messenger: Arc<OnionMessenger>,
om_mailbox: Option<Arc<OnionMessageMailbox>>, runtime: Arc<Runtime>, logger: L,
config: Arc<Config>,
om_mailbox: Option<Arc<OnionMessageMailbox>>, prober: Option<Arc<Prober>>,
runtime: Arc<Runtime>, logger: L, config: Arc<Config>,
) -> Self {
Self {
event_queue,
Expand All@@ -571,12 +573,13 @@ where
payment_store,
peer_store,
keys_manager,
logger,
runtime,
config,
static_invoice_store,
onion_messenger,
om_mailbox,
prober,
runtime,
logger,
config,
}
}

Expand DownExpand Up@@ -1208,8 +1211,16 @@ where

LdkEvent::PaymentPathSuccessful { .. } => {},
LdkEvent::PaymentPathFailed { .. } => {},
LdkEvent::ProbeSuccessful { .. } => {},
LdkEvent::ProbeFailed { .. } => {},
LdkEvent::ProbeSuccessful { path, payment_id, .. } => {
if let Some(prober) = &self.prober {
prober.handle_background_probe_successful(&path, payment_id);
}
},
LdkEvent::ProbeFailed { path, payment_id, .. } => {
if let Some(prober) = &self.prober {
prober.handle_background_probe_failed(&path, payment_id);
}
},
LdkEvent::HTLCHandlingFailed { failure_type, .. } => {
self.liquidity_source
.lsps2_service()
Expand Down
1 change: 1 addition & 0 deletions src/ffi/types.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -149,6 +149,7 @@ pub use crate::entropy::{generate_entropy_mnemonic, NodeEntropy, WordCount};
use crate::error::Error;
pub use crate::liquidity::LSPS1OrderStatus;
pub use crate::logger::{LogLevel, LogRecord, LogWriter};
pub use crate::probing::ProbingConfig;
use crate::{hex_utils, SocketAddress, UserChannelId};

uniffi::custom_type!(PublicKey, String, {
Expand Down
19 changes: 19 additions & 0 deletions src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -101,10 +101,12 @@ pub mod logger;
mod message_handler;
pub mod payment;
mod peer_store;
pub mod probing;
mod runtime;
mod scoring;
mod tx_broadcaster;
mod types;
mod util;
mod wallet;

use std::default::Default;
Expand DownExpand Up@@ -172,6 +174,9 @@ use payment::{
UnifiedPayment,
};
use peer_store::{PeerInfo, PeerStore};
#[cfg(feature = "uniffi")]
pub use probing::ArcedProbingConfigBuilder as ProbingConfigBuilder;
use probing::{run_prober, Prober};
use runtime::Runtime;
pub use tokio;
use types::{
Expand DownExpand Up@@ -250,6 +255,7 @@ pub struct Node {
om_mailbox: Option<Arc<OnionMessageMailbox>>,
async_payments_role: Option<AsyncPaymentsRole>,
hrn_resolver: HRNResolver,
prober: Option<Arc<Prober>>,
#[cfg(cycle_tests)]
_leak_checker: LeakChecker,
}
Expand DownExpand Up@@ -610,11 +616,19 @@ impl Node {
static_invoice_store,
Arc::clone(&self.onion_messenger),
self.om_mailbox.clone(),
self.prober.clone(),
Arc::clone(&self.runtime),
Arc::clone(&self.logger),
Arc::clone(&self.config),
));

if let Some(prober) = self.prober.clone() {
let stop_rx = self.stop_sender.subscribe();
self.runtime.spawn_cancellable_background_task(async move {
run_prober(prober, stop_rx).await;
});
}

// Setup background processing
let background_persister = Arc::clone(&self.kv_store);
let background_event_handler = Arc::clone(&event_handler);
Expand DownExpand Up@@ -1145,6 +1159,11 @@ impl Node {
))
}

/// Returns a reference to the [`Prober`], or `None` if no probing strategy is configured.
pub fn prober(&self) -> Option<&Prober> {
self.prober.as_deref()
}

/// Retrieve a list of known channels.
pub fn list_channels(&self) -> Vec<ChannelDetails> {
self.channel_manager
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions bindings/ldk_node.udl
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,6 +13,8 @@ typedef dictionary TorConfig;

typedef interface NodeEntropy;

typedef interface ProbingConfig;

typedef enum WordCount;

[Remote]
Expand All@@ -32,6 +34,18 @@ interface LogWriter {
void log(LogRecord record);
};

interface ProbingConfigBuilder {
[Name=high_degree]
constructor(u64 top_node_count);
[Name=random_walk]
constructor(u64 max_hops);
void set_interval(u64 secs);
void set_max_locked_msat(u64 max_msat);
void set_diversity_penalty_msat(u64 penalty_msat);
void set_cooldown(u64 secs);
ProbingConfig build();
};

interface Builder {
constructor();
[Name=from_config]
Expand DownExpand Up@@ -59,6 +73,7 @@ interface Builder {
void set_node_alias(string node_alias);
[Throws=BuildError]
void set_async_payments_role(AsyncPaymentsRole? role);
void set_probing_config(ProbingConfig config);
[Throws=BuildError]
Node build(NodeEntropy node_entropy);
[Throws=BuildError]
Expand Down
93 changes: 91 additions & 2 deletions src/builder.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -50,6 +50,7 @@ use crate::config::{
default_user_config, may_announce_channel, AnnounceError, AsyncPaymentsRole,
BitcoindRestClientConfig, Config, ElectrumSyncConfig, EsploraSyncConfig, HRNResolverConfig,
TorConfig, DEFAULT_ESPLORA_SERVER_URL, DEFAULT_LOG_FILENAME, DEFAULT_LOG_LEVEL,
DEFAULT_MAX_PROBE_AMOUNT_MSAT, DEFAULT_MIN_PROBE_AMOUNT_MSAT,
};
use crate::connection::ConnectionManager;
use crate::entropy::NodeEntropy;
Expand All@@ -74,6 +75,10 @@ use crate::logger::{log_error, LdkLogger, LogLevel, LogWriter, Logger};
use crate::message_handler::NodeCustomMessageHandler;
use crate::payment::asynchronous::om_mailbox::OnionMessageMailbox;
use crate::peer_store::PeerStore;
use crate::probing::{
HighDegreeStrategy, Prober, ProbingConfig, ProbingStrategy, ProbingStrategyKind,
RandomWalkStrategy,
};
use crate::runtime::{Runtime, RuntimeSpawner};
use crate::tx_broadcaster::TransactionBroadcaster;
use crate::types::{
Expand DownExpand Up@@ -306,6 +311,7 @@ pub struct NodeBuilder {
async_payments_role: Option<AsyncPaymentsRole>,
runtime_handle: Option<tokio::runtime::Handle>,
pathfinding_scores_sync_config: Option<PathfindingScoresSyncConfig>,
probing_config: Option<ProbingConfig>,
}

impl NodeBuilder {
Expand All@@ -323,6 +329,7 @@ impl NodeBuilder {
let log_writer_config = None;
let runtime_handle = None;
let pathfinding_scores_sync_config = None;
let probing_config = None;
Self {
config,
chain_data_source_config,
Expand All@@ -332,6 +339,7 @@ impl NodeBuilder {
runtime_handle,
async_payments_role: None,
pathfinding_scores_sync_config,
probing_config,
}
}

Expand DownExpand Up@@ -629,6 +637,31 @@ impl NodeBuilder {
Ok(self)
}

/// Sets background probing config.
///
/// Use [`ProbingConfigBuilder`] to build the configuration:
/// ```no_run
/// # #[cfg(not(feature = "uniffi"))]
/// # {
/// use std::time::Duration;
/// use ldk_node::Builder;
/// use ldk_node::probing::ProbingConfigBuilder;
///
/// let mut builder = Builder::new();
/// builder.set_probing_config(
/// ProbingConfigBuilder::high_degree(100)
/// .interval(Duration::from_secs(30))
/// .build()
/// );
/// # }
/// ```
///
/// [`ProbingConfigBuilder`]: crate::probing::ProbingConfigBuilder
pub fn set_probing_config(&mut self, config: ProbingConfig) -> &mut Self {
self.probing_config = Some(config);
self
}

/// Builds a [`Node`] instance with a [`SqliteStore`] backend and according to the options
/// previously configured.
pub fn build(&self, node_entropy: NodeEntropy) -> Result<Node, BuildError> {
Expand DownExpand Up@@ -868,6 +901,7 @@ impl NodeBuilder {
self.gossip_source_config.as_ref(),
self.liquidity_source_config.as_ref(),
self.pathfinding_scores_sync_config.as_ref(),
self.probing_config.as_ref(),
self.async_payments_role,
seed_bytes,
runtime,
Expand DownExpand Up@@ -1166,6 +1200,15 @@ impl ArcedNodeBuilder {
self.inner.write().expect("lock").set_async_payments_role(role).map(|_| ())
}

/// Configures background probing.
///
/// Use [`ProbingConfigBuilder`] to build the configuration.
///
/// [`ProbingConfigBuilder`]: crate::probing::ProbingConfigBuilder
pub fn set_probing_config(&self, config: Arc<ProbingConfig>) {
self.inner.write().expect("lock").set_probing_config((*config).clone());
}

/// Builds a [`Node`] instance with a [`SqliteStore`] backend and according to the options
/// previously configured.
pub fn build(&self, node_entropy: Arc<NodeEntropy>) -> Result<Arc<Node>, BuildError> {
Expand DownExpand Up@@ -1361,8 +1404,8 @@ fn build_with_store_internal(
gossip_source_config: Option<&GossipSourceConfig>,
liquidity_source_config: Option<&LiquiditySourceConfig>,
pathfinding_scores_sync_config: Option<&PathfindingScoresSyncConfig>,
async_payments_role: Option<AsyncPaymentsRole>, seed_bytes: [u8; 64], runtime: Arc<Runtime>,
logger: Arc<Logger>, kv_store: Arc<DynStore>,
probing_config: Option<&ProbingConfig>, async_payments_role: Option<AsyncPaymentsRole>,
seed_bytes: [u8; 64], runtime: Arc<Runtime>, logger: Arc<Logger>, kv_store: Arc<DynStore>,
) -> Result<Node, BuildError> {
optionally_install_rustls_cryptoprovider();

Expand DownExpand Up@@ -2219,6 +2262,51 @@ fn build_with_store_internal(
_leak_checker.0.push(Arc::downgrade(&wallet) as Weak<dyn Any + Send + Sync>);
}

let prober = probing_config.map(|probing_cfg| {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Would be better to move this up before the leak checker setup.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

moved

let strategy: Arc<dyn ProbingStrategy> = match &probing_cfg.kind {
ProbingStrategyKind::HighDegree { top_node_count } => {
// Dedicated router for probing so the diversity penalty doesn't interfere
// with real payments; shares the scorer so probe results still train it.
let mut probing_fee_params = ProbabilisticScoringFeeParameters::default();
Comment thread
randomlogin marked this conversation as resolved.
if let Some(penalty) = probing_cfg.diversity_penalty_msat {
probing_fee_params.probing_diversity_penalty_msat = penalty;
}
let probing_router = Arc::new(DefaultRouter::new(
Arc::clone(&network_graph),
Arc::clone(&logger),
Arc::clone(&keys_manager),
Arc::clone(&scorer),
probing_fee_params,
));
Arc::new(HighDegreeStrategy::new(
Arc::clone(&network_graph),
Arc::clone(&channel_manager),
probing_router,
*top_node_count,
DEFAULT_MIN_PROBE_AMOUNT_MSAT,
DEFAULT_MAX_PROBE_AMOUNT_MSAT,
probing_cfg.cooldown,
config.probing_liquidity_limit_multiplier,
))
},
ProbingStrategyKind::RandomWalk { max_hops } => Arc::new(RandomWalkStrategy::new(
Arc::clone(&network_graph),
Arc::clone(&channel_manager),
*max_hops,
DEFAULT_MIN_PROBE_AMOUNT_MSAT,
DEFAULT_MAX_PROBE_AMOUNT_MSAT,
)),
ProbingStrategyKind::Custom(s) => Arc::clone(s),
};
Arc::new(Prober {
channel_manager: Arc::clone(&channel_manager),
logger: Arc::clone(&logger),
strategy,
interval: probing_cfg.interval,
max_locked_msat: probing_cfg.max_locked_msat,
})
});

Ok(Node {
runtime,
stop_sender,
Expand DownExpand Up@@ -2252,6 +2340,7 @@ fn build_with_store_internal(
om_mailbox,
async_payments_role,
hrn_resolver,
prober,
#[cfg(cycle_tests)]
_leak_checker,
})
Expand Down
6 changes: 6 additions & 0 deletions src/config.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,6 +28,12 @@ const DEFAULT_BDK_WALLET_SYNC_INTERVAL_SECS: u64 = 80;
const DEFAULT_LDK_WALLET_SYNC_INTERVAL_SECS: u64 = 30;
const DEFAULT_FEE_RATE_CACHE_UPDATE_INTERVAL_SECS: u64 = 60 * 10;
const DEFAULT_PROBING_LIQUIDITY_LIMIT_MULTIPLIER: u64 = 3;
pub(crate) const DEFAULT_PROBING_INTERVAL_SECS: u64 = 10;
pub(crate) const MIN_PROBING_INTERVAL: Duration = Duration::from_millis(100);
pub(crate) const DEFAULT_PROBED_NODE_COOLDOWN_SECS: u64 = 60 * 60; // 1 hour
pub(crate) const DEFAULT_MAX_PROBE_LOCKED_MSAT: u64 = 100_000_000; // 100k sats
pub(crate) const DEFAULT_MIN_PROBE_AMOUNT_MSAT: u64 = 1_000_000; // 1k sats
pub(crate) const DEFAULT_MAX_PROBE_AMOUNT_MSAT: u64 = 10_000_000; // 10k sats
const DEFAULT_ANCHOR_PER_CHANNEL_RESERVE_SATS: u64 = 25_000;

// The default timeout after which we abort a wallet syncing operation.
Expand Down
31 changes: 21 additions & 10 deletions src/event.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -52,6 +52,7 @@ use crate::payment::store::{
PaymentDetails, PaymentDetailsUpdate, PaymentDirection, PaymentKind, PaymentStatus,
};
use crate::payment::PaymentMetadata;
use crate::probing::Prober;
use crate::runtime::Runtime;
use crate::types::{
CustomTlvRecord, DynStore, KeysManager, OnionMessenger, PaymentStore, Sweeper, Wallet,
Expand DownExpand Up@@ -536,12 +537,13 @@ where
payment_store: Arc<PaymentStore>,
peer_store: Arc<PeerStore<L>>,
keys_manager: Arc<KeysManager>,
runtime: Arc<Runtime>,
logger: L,
config: Arc<Config>,
static_invoice_store: Option<StaticInvoiceStore>,
onion_messenger: Arc<OnionMessenger>,
om_mailbox: Option<Arc<OnionMessageMailbox>>,
prober: Option<Arc<Prober>>,
runtime: Arc<Runtime>,
logger: L,
config: Arc<Config>,
}

impl<L: Deref + Clone + Sync + Send + 'static> EventHandler<L>
Expand All@@ -556,8 +558,8 @@ where
liquidity_source: Arc<LiquiditySource<Arc<Logger>>>, payment_store: Arc<PaymentStore>,
peer_store: Arc<PeerStore<L>>, keys_manager: Arc<KeysManager>,
static_invoice_store: Option<StaticInvoiceStore>, onion_messenger: Arc<OnionMessenger>,
om_mailbox: Option<Arc<OnionMessageMailbox>>, runtime: Arc<Runtime>, logger: L,
config: Arc<Config>,
om_mailbox: Option<Arc<OnionMessageMailbox>>, prober: Option<Arc<Prober>>,
runtime: Arc<Runtime>, logger: L, config: Arc<Config>,
) -> Self {
Self {
event_queue,
Expand All@@ -571,12 +573,13 @@ where
payment_store,
peer_store,
keys_manager,
logger,
runtime,
config,
static_invoice_store,
onion_messenger,
om_mailbox,
prober,
runtime,
logger,
config,
}
}

Expand DownExpand Up@@ -1208,8 +1211,16 @@ where

LdkEvent::PaymentPathSuccessful { .. } => {},
LdkEvent::PaymentPathFailed { .. } => {},
LdkEvent::ProbeSuccessful { .. } => {},
LdkEvent::ProbeFailed { .. } => {},
LdkEvent::ProbeSuccessful { path, payment_id, .. } => {
if let Some(prober) = &self.prober {
prober.handle_background_probe_successful(&path, payment_id);
}
},
LdkEvent::ProbeFailed { path, payment_id, .. } => {
if let Some(prober) = &self.prober {
prober.handle_background_probe_failed(&path, payment_id);
}
},
LdkEvent::HTLCHandlingFailed { failure_type, .. } => {
self.liquidity_source
.lsps2_service()
Expand Down
1 change: 1 addition & 0 deletions src/ffi/types.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -149,6 +149,7 @@ pub use crate::entropy::{generate_entropy_mnemonic, NodeEntropy, WordCount};
use crate::error::Error;
pub use crate::liquidity::LSPS1OrderStatus;
pub use crate::logger::{LogLevel, LogRecord, LogWriter};
pub use crate::probing::ProbingConfig;
use crate::{hex_utils, SocketAddress, UserChannelId};

uniffi::custom_type!(PublicKey, String, {
Expand Down
19 changes: 19 additions & 0 deletions src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -101,10 +101,12 @@ pub mod logger;
mod message_handler;
pub mod payment;
mod peer_store;
pub mod probing;
mod runtime;
mod scoring;
mod tx_broadcaster;
mod types;
mod util;
mod wallet;

use std::default::Default;
Expand DownExpand Up@@ -172,6 +174,9 @@ use payment::{
UnifiedPayment,
};
use peer_store::{PeerInfo, PeerStore};
#[cfg(feature = "uniffi")]
pub use probing::ArcedProbingConfigBuilder as ProbingConfigBuilder;
use probing::{run_prober, Prober};
use runtime::Runtime;
pub use tokio;
use types::{
Expand DownExpand Up@@ -250,6 +255,7 @@ pub struct Node {
om_mailbox: Option<Arc<OnionMessageMailbox>>,
async_payments_role: Option<AsyncPaymentsRole>,
hrn_resolver: HRNResolver,
prober: Option<Arc<Prober>>,
#[cfg(cycle_tests)]
_leak_checker: LeakChecker,
}
Expand DownExpand Up@@ -610,11 +616,19 @@ impl Node {
static_invoice_store,
Arc::clone(&self.onion_messenger),
self.om_mailbox.clone(),
self.prober.clone(),
Arc::clone(&self.runtime),
Arc::clone(&self.logger),
Arc::clone(&self.config),
));

if let Some(prober) = self.prober.clone() {
let stop_rx = self.stop_sender.subscribe();
self.runtime.spawn_cancellable_background_task(async move {
run_prober(prober, stop_rx).await;
});
}

// Setup background processing
let background_persister = Arc::clone(&self.kv_store);
let background_event_handler = Arc::clone(&event_handler);
Expand DownExpand Up@@ -1145,6 +1159,11 @@ impl Node {
))
}

/// Returns a reference to the [`Prober`], or `None` if no probing strategy is configured.
pub fn prober(&self) -> Option<&Prober> {
self.prober.as_deref()
}

/// Retrieve a list of known channels.
pub fn list_channels(&self) -> Vec<ChannelDetails> {
self.channel_manager
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions bindings/ldk_node.udl
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,6 +13,8 @@ typedef dictionary TorConfig;

typedef interface NodeEntropy;

typedef interface ProbingConfig;

typedef enum WordCount;

[Remote]
Expand All@@ -32,6 +34,18 @@ interface LogWriter {
void log(LogRecord record);
};

interface ProbingConfigBuilder {
[Name=high_degree]
constructor(u64 top_node_count);
[Name=random_walk]
constructor(u64 max_hops);
void set_interval(u64 secs);
void set_max_locked_msat(u64 max_msat);
void set_diversity_penalty_msat(u64 penalty_msat);
void set_cooldown(u64 secs);
ProbingConfig build();
};

interface Builder {
constructor();
[Name=from_config]
Expand DownExpand Up@@ -59,6 +73,7 @@ interface Builder {
void set_node_alias(string node_alias);
[Throws=BuildError]
void set_async_payments_role(AsyncPaymentsRole? role);
void set_probing_config(ProbingConfig config);
[Throws=BuildError]
Node build(NodeEntropy node_entropy);
[Throws=BuildError]
Expand Down
93 changes: 91 additions & 2 deletions src/builder.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -50,6 +50,7 @@ use crate::config::{
default_user_config, may_announce_channel, AnnounceError, AsyncPaymentsRole,
BitcoindRestClientConfig, Config, ElectrumSyncConfig, EsploraSyncConfig, HRNResolverConfig,
TorConfig, DEFAULT_ESPLORA_SERVER_URL, DEFAULT_LOG_FILENAME, DEFAULT_LOG_LEVEL,
DEFAULT_MAX_PROBE_AMOUNT_MSAT, DEFAULT_MIN_PROBE_AMOUNT_MSAT,
};
use crate::connection::ConnectionManager;
use crate::entropy::NodeEntropy;
Expand All@@ -74,6 +75,10 @@ use crate::logger::{log_error, LdkLogger, LogLevel, LogWriter, Logger};
use crate::message_handler::NodeCustomMessageHandler;
use crate::payment::asynchronous::om_mailbox::OnionMessageMailbox;
use crate::peer_store::PeerStore;
use crate::probing::{
HighDegreeStrategy, Prober, ProbingConfig, ProbingStrategy, ProbingStrategyKind,
RandomWalkStrategy,
};
use crate::runtime::{Runtime, RuntimeSpawner};
use crate::tx_broadcaster::TransactionBroadcaster;
use crate::types::{
Expand DownExpand Up@@ -306,6 +311,7 @@ pub struct NodeBuilder {
async_payments_role: Option<AsyncPaymentsRole>,
runtime_handle: Option<tokio::runtime::Handle>,
pathfinding_scores_sync_config: Option<PathfindingScoresSyncConfig>,
probing_config: Option<ProbingConfig>,
}

impl NodeBuilder {
Expand All@@ -323,6 +329,7 @@ impl NodeBuilder {
let log_writer_config = None;
let runtime_handle = None;
let pathfinding_scores_sync_config = None;
let probing_config = None;
Self {
config,
chain_data_source_config,
Expand All@@ -332,6 +339,7 @@ impl NodeBuilder {
runtime_handle,
async_payments_role: None,
pathfinding_scores_sync_config,
probing_config,
}
}

Expand DownExpand Up@@ -629,6 +637,31 @@ impl NodeBuilder {
Ok(self)
}

/// Sets background probing config.
///
/// Use [`ProbingConfigBuilder`] to build the configuration:
/// ```no_run
/// # #[cfg(not(feature = "uniffi"))]
/// # {
/// use std::time::Duration;
/// use ldk_node::Builder;
/// use ldk_node::probing::ProbingConfigBuilder;
///
/// let mut builder = Builder::new();
/// builder.set_probing_config(
/// ProbingConfigBuilder::high_degree(100)
/// .interval(Duration::from_secs(30))
/// .build()
/// );
/// # }
/// ```
///
/// [`ProbingConfigBuilder`]: crate::probing::ProbingConfigBuilder
pub fn set_probing_config(&mut self, config: ProbingConfig) -> &mut Self {
self.probing_config = Some(config);
self
}

/// Builds a [`Node`] instance with a [`SqliteStore`] backend and according to the options
/// previously configured.
pub fn build(&self, node_entropy: NodeEntropy) -> Result<Node, BuildError> {
Expand DownExpand Up@@ -868,6 +901,7 @@ impl NodeBuilder {
self.gossip_source_config.as_ref(),
self.liquidity_source_config.as_ref(),
self.pathfinding_scores_sync_config.as_ref(),
self.probing_config.as_ref(),
self.async_payments_role,
seed_bytes,
runtime,
Expand DownExpand Up@@ -1166,6 +1200,15 @@ impl ArcedNodeBuilder {
self.inner.write().expect("lock").set_async_payments_role(role).map(|_| ())
}

/// Configures background probing.
///
/// Use [`ProbingConfigBuilder`] to build the configuration.
///
/// [`ProbingConfigBuilder`]: crate::probing::ProbingConfigBuilder
pub fn set_probing_config(&self, config: Arc<ProbingConfig>) {
self.inner.write().expect("lock").set_probing_config((*config).clone());
}

/// Builds a [`Node`] instance with a [`SqliteStore`] backend and according to the options
/// previously configured.
pub fn build(&self, node_entropy: Arc<NodeEntropy>) -> Result<Arc<Node>, BuildError> {
Expand DownExpand Up@@ -1361,8 +1404,8 @@ fn build_with_store_internal(
gossip_source_config: Option<&GossipSourceConfig>,
liquidity_source_config: Option<&LiquiditySourceConfig>,
pathfinding_scores_sync_config: Option<&PathfindingScoresSyncConfig>,
async_payments_role: Option<AsyncPaymentsRole>, seed_bytes: [u8; 64], runtime: Arc<Runtime>,
logger: Arc<Logger>, kv_store: Arc<DynStore>,
probing_config: Option<&ProbingConfig>, async_payments_role: Option<AsyncPaymentsRole>,
seed_bytes: [u8; 64], runtime: Arc<Runtime>, logger: Arc<Logger>, kv_store: Arc<DynStore>,
) -> Result<Node, BuildError> {
optionally_install_rustls_cryptoprovider();

Expand DownExpand Up@@ -2219,6 +2262,51 @@ fn build_with_store_internal(
_leak_checker.0.push(Arc::downgrade(&wallet) as Weak<dyn Any + Send + Sync>);
}

let prober = probing_config.map(|probing_cfg| {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Would be better to move this up before the leak checker setup.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

moved

let strategy: Arc<dyn ProbingStrategy> = match &probing_cfg.kind {
ProbingStrategyKind::HighDegree { top_node_count } => {
// Dedicated router for probing so the diversity penalty doesn't interfere
// with real payments; shares the scorer so probe results still train it.
let mut probing_fee_params = ProbabilisticScoringFeeParameters::default();
Comment thread
randomlogin marked this conversation as resolved.
if let Some(penalty) = probing_cfg.diversity_penalty_msat {
probing_fee_params.probing_diversity_penalty_msat = penalty;
}
let probing_router = Arc::new(DefaultRouter::new(
Arc::clone(&network_graph),
Arc::clone(&logger),
Arc::clone(&keys_manager),
Arc::clone(&scorer),
probing_fee_params,
));
Arc::new(HighDegreeStrategy::new(
Arc::clone(&network_graph),
Arc::clone(&channel_manager),
probing_router,
*top_node_count,
DEFAULT_MIN_PROBE_AMOUNT_MSAT,
DEFAULT_MAX_PROBE_AMOUNT_MSAT,
probing_cfg.cooldown,
config.probing_liquidity_limit_multiplier,
))
},
ProbingStrategyKind::RandomWalk { max_hops } => Arc::new(RandomWalkStrategy::new(
Arc::clone(&network_graph),
Arc::clone(&channel_manager),
*max_hops,
DEFAULT_MIN_PROBE_AMOUNT_MSAT,
DEFAULT_MAX_PROBE_AMOUNT_MSAT,
)),
ProbingStrategyKind::Custom(s) => Arc::clone(s),
};
Arc::new(Prober {
channel_manager: Arc::clone(&channel_manager),
logger: Arc::clone(&logger),
strategy,
interval: probing_cfg.interval,
max_locked_msat: probing_cfg.max_locked_msat,
})
});

Ok(Node {
runtime,
stop_sender,
Expand DownExpand Up@@ -2252,6 +2340,7 @@ fn build_with_store_internal(
om_mailbox,
async_payments_role,
hrn_resolver,
prober,
#[cfg(cycle_tests)]
_leak_checker,
})
Expand Down
6 changes: 6 additions & 0 deletions src/config.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,6 +28,12 @@ const DEFAULT_BDK_WALLET_SYNC_INTERVAL_SECS: u64 = 80;
const DEFAULT_LDK_WALLET_SYNC_INTERVAL_SECS: u64 = 30;
const DEFAULT_FEE_RATE_CACHE_UPDATE_INTERVAL_SECS: u64 = 60 * 10;
const DEFAULT_PROBING_LIQUIDITY_LIMIT_MULTIPLIER: u64 = 3;
pub(crate) const DEFAULT_PROBING_INTERVAL_SECS: u64 = 10;
pub(crate) const MIN_PROBING_INTERVAL: Duration = Duration::from_millis(100);
pub(crate) const DEFAULT_PROBED_NODE_COOLDOWN_SECS: u64 = 60 * 60; // 1 hour
pub(crate) const DEFAULT_MAX_PROBE_LOCKED_MSAT: u64 = 100_000_000; // 100k sats
pub(crate) const DEFAULT_MIN_PROBE_AMOUNT_MSAT: u64 = 1_000_000; // 1k sats
pub(crate) const DEFAULT_MAX_PROBE_AMOUNT_MSAT: u64 = 10_000_000; // 10k sats
const DEFAULT_ANCHOR_PER_CHANNEL_RESERVE_SATS: u64 = 25_000;

// The default timeout after which we abort a wallet syncing operation.
Expand Down
31 changes: 21 additions & 10 deletions src/event.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -52,6 +52,7 @@ use crate::payment::store::{
PaymentDetails, PaymentDetailsUpdate, PaymentDirection, PaymentKind, PaymentStatus,
};
use crate::payment::PaymentMetadata;
use crate::probing::Prober;
use crate::runtime::Runtime;
use crate::types::{
CustomTlvRecord, DynStore, KeysManager, OnionMessenger, PaymentStore, Sweeper, Wallet,
Expand DownExpand Up@@ -536,12 +537,13 @@ where
payment_store: Arc<PaymentStore>,
peer_store: Arc<PeerStore<L>>,
keys_manager: Arc<KeysManager>,
runtime: Arc<Runtime>,
logger: L,
config: Arc<Config>,
static_invoice_store: Option<StaticInvoiceStore>,
onion_messenger: Arc<OnionMessenger>,
om_mailbox: Option<Arc<OnionMessageMailbox>>,
prober: Option<Arc<Prober>>,
runtime: Arc<Runtime>,
logger: L,
config: Arc<Config>,
}

impl<L: Deref + Clone + Sync + Send + 'static> EventHandler<L>
Expand All@@ -556,8 +558,8 @@ where
liquidity_source: Arc<LiquiditySource<Arc<Logger>>>, payment_store: Arc<PaymentStore>,
peer_store: Arc<PeerStore<L>>, keys_manager: Arc<KeysManager>,
static_invoice_store: Option<StaticInvoiceStore>, onion_messenger: Arc<OnionMessenger>,
om_mailbox: Option<Arc<OnionMessageMailbox>>, runtime: Arc<Runtime>, logger: L,
config: Arc<Config>,
om_mailbox: Option<Arc<OnionMessageMailbox>>, prober: Option<Arc<Prober>>,
runtime: Arc<Runtime>, logger: L, config: Arc<Config>,
) -> Self {
Self {
event_queue,
Expand All@@ -571,12 +573,13 @@ where
payment_store,
peer_store,
keys_manager,
logger,
runtime,
config,
static_invoice_store,
onion_messenger,
om_mailbox,
prober,
runtime,
logger,
config,
}
}

Expand DownExpand Up@@ -1208,8 +1211,16 @@ where

LdkEvent::PaymentPathSuccessful { .. } => {},
LdkEvent::PaymentPathFailed { .. } => {},
LdkEvent::ProbeSuccessful { .. } => {},
LdkEvent::ProbeFailed { .. } => {},
LdkEvent::ProbeSuccessful { path, payment_id, .. } => {
if let Some(prober) = &self.prober {
prober.handle_background_probe_successful(&path, payment_id);
}
},
LdkEvent::ProbeFailed { path, payment_id, .. } => {
if let Some(prober) = &self.prober {
prober.handle_background_probe_failed(&path, payment_id);
}
},
LdkEvent::HTLCHandlingFailed { failure_type, .. } => {
self.liquidity_source
.lsps2_service()
Expand Down
1 change: 1 addition & 0 deletions src/ffi/types.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -149,6 +149,7 @@ pub use crate::entropy::{generate_entropy_mnemonic, NodeEntropy, WordCount};
use crate::error::Error;
pub use crate::liquidity::LSPS1OrderStatus;
pub use crate::logger::{LogLevel, LogRecord, LogWriter};
pub use crate::probing::ProbingConfig;
use crate::{hex_utils, SocketAddress, UserChannelId};

uniffi::custom_type!(PublicKey, String, {
Expand Down
19 changes: 19 additions & 0 deletions src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -101,10 +101,12 @@ pub mod logger;
mod message_handler;
pub mod payment;
mod peer_store;
pub mod probing;
mod runtime;
mod scoring;
mod tx_broadcaster;
mod types;
mod util;
mod wallet;

use std::default::Default;
Expand DownExpand Up@@ -172,6 +174,9 @@ use payment::{
UnifiedPayment,
};
use peer_store::{PeerInfo, PeerStore};
#[cfg(feature = "uniffi")]
pub use probing::ArcedProbingConfigBuilder as ProbingConfigBuilder;
use probing::{run_prober, Prober};
use runtime::Runtime;
pub use tokio;
use types::{
Expand DownExpand Up@@ -250,6 +255,7 @@ pub struct Node {
om_mailbox: Option<Arc<OnionMessageMailbox>>,
async_payments_role: Option<AsyncPaymentsRole>,
hrn_resolver: HRNResolver,
prober: Option<Arc<Prober>>,
#[cfg(cycle_tests)]
_leak_checker: LeakChecker,
}
Expand DownExpand Up@@ -610,11 +616,19 @@ impl Node {
static_invoice_store,
Arc::clone(&self.onion_messenger),
self.om_mailbox.clone(),
self.prober.clone(),
Arc::clone(&self.runtime),
Arc::clone(&self.logger),
Arc::clone(&self.config),
));

if let Some(prober) = self.prober.clone() {
let stop_rx = self.stop_sender.subscribe();
self.runtime.spawn_cancellable_background_task(async move {
run_prober(prober, stop_rx).await;
});
}

// Setup background processing
let background_persister = Arc::clone(&self.kv_store);
let background_event_handler = Arc::clone(&event_handler);
Expand DownExpand Up@@ -1145,6 +1159,11 @@ impl Node {
))
}

/// Returns a reference to the [`Prober`], or `None` if no probing strategy is configured.
pub fn prober(&self) -> Option<&Prober> {
self.prober.as_deref()
}

/// Retrieve a list of known channels.
pub fn list_channels(&self) -> Vec<ChannelDetails> {
self.channel_manager
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions bindings/ldk_node.udl
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,6 +13,8 @@ typedef dictionary TorConfig;

typedef interface NodeEntropy;

typedef interface ProbingConfig;

typedef enum WordCount;

[Remote]
Expand All@@ -32,6 +34,18 @@ interface LogWriter {
void log(LogRecord record);
};

interface ProbingConfigBuilder {
[Name=high_degree]
constructor(u64 top_node_count);
[Name=random_walk]
constructor(u64 max_hops);
void set_interval(u64 secs);
void set_max_locked_msat(u64 max_msat);
void set_diversity_penalty_msat(u64 penalty_msat);
void set_cooldown(u64 secs);
ProbingConfig build();
};

interface Builder {
constructor();
[Name=from_config]
Expand DownExpand Up@@ -59,6 +73,7 @@ interface Builder {
void set_node_alias(string node_alias);
[Throws=BuildError]
void set_async_payments_role(AsyncPaymentsRole? role);
void set_probing_config(ProbingConfig config);
[Throws=BuildError]
Node build(NodeEntropy node_entropy);
[Throws=BuildError]
Expand Down
93 changes: 91 additions & 2 deletions src/builder.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -50,6 +50,7 @@ use crate::config::{
default_user_config, may_announce_channel, AnnounceError, AsyncPaymentsRole,
BitcoindRestClientConfig, Config, ElectrumSyncConfig, EsploraSyncConfig, HRNResolverConfig,
TorConfig, DEFAULT_ESPLORA_SERVER_URL, DEFAULT_LOG_FILENAME, DEFAULT_LOG_LEVEL,
DEFAULT_MAX_PROBE_AMOUNT_MSAT, DEFAULT_MIN_PROBE_AMOUNT_MSAT,
};
use crate::connection::ConnectionManager;
use crate::entropy::NodeEntropy;
Expand All@@ -74,6 +75,10 @@ use crate::logger::{log_error, LdkLogger, LogLevel, LogWriter, Logger};
use crate::message_handler::NodeCustomMessageHandler;
use crate::payment::asynchronous::om_mailbox::OnionMessageMailbox;
use crate::peer_store::PeerStore;
use crate::probing::{
HighDegreeStrategy, Prober, ProbingConfig, ProbingStrategy, ProbingStrategyKind,
RandomWalkStrategy,
};
use crate::runtime::{Runtime, RuntimeSpawner};
use crate::tx_broadcaster::TransactionBroadcaster;
use crate::types::{
Expand DownExpand Up@@ -306,6 +311,7 @@ pub struct NodeBuilder {
async_payments_role: Option<AsyncPaymentsRole>,
runtime_handle: Option<tokio::runtime::Handle>,
pathfinding_scores_sync_config: Option<PathfindingScoresSyncConfig>,
probing_config: Option<ProbingConfig>,
}

impl NodeBuilder {
Expand All@@ -323,6 +329,7 @@ impl NodeBuilder {
let log_writer_config = None;
let runtime_handle = None;
let pathfinding_scores_sync_config = None;
let probing_config = None;
Self {
config,
chain_data_source_config,
Expand All@@ -332,6 +339,7 @@ impl NodeBuilder {
runtime_handle,
async_payments_role: None,
pathfinding_scores_sync_config,
probing_config,
}
}

Expand DownExpand Up@@ -629,6 +637,31 @@ impl NodeBuilder {
Ok(self)
}

/// Sets background probing config.
///
/// Use [`ProbingConfigBuilder`] to build the configuration:
/// ```no_run
/// # #[cfg(not(feature = "uniffi"))]
/// # {
/// use std::time::Duration;
/// use ldk_node::Builder;
/// use ldk_node::probing::ProbingConfigBuilder;
///
/// let mut builder = Builder::new();
/// builder.set_probing_config(
/// ProbingConfigBuilder::high_degree(100)
/// .interval(Duration::from_secs(30))
/// .build()
/// );
/// # }
/// ```
///
/// [`ProbingConfigBuilder`]: crate::probing::ProbingConfigBuilder
pub fn set_probing_config(&mut self, config: ProbingConfig) -> &mut Self {
self.probing_config = Some(config);
self
}

/// Builds a [`Node`] instance with a [`SqliteStore`] backend and according to the options
/// previously configured.
pub fn build(&self, node_entropy: NodeEntropy) -> Result<Node, BuildError> {
Expand DownExpand Up@@ -868,6 +901,7 @@ impl NodeBuilder {
self.gossip_source_config.as_ref(),
self.liquidity_source_config.as_ref(),
self.pathfinding_scores_sync_config.as_ref(),
self.probing_config.as_ref(),
self.async_payments_role,
seed_bytes,
runtime,
Expand DownExpand Up@@ -1166,6 +1200,15 @@ impl ArcedNodeBuilder {
self.inner.write().expect("lock").set_async_payments_role(role).map(|_| ())
}

/// Configures background probing.
///
/// Use [`ProbingConfigBuilder`] to build the configuration.
///
/// [`ProbingConfigBuilder`]: crate::probing::ProbingConfigBuilder
pub fn set_probing_config(&self, config: Arc<ProbingConfig>) {
self.inner.write().expect("lock").set_probing_config((*config).clone());
}

/// Builds a [`Node`] instance with a [`SqliteStore`] backend and according to the options
/// previously configured.
pub fn build(&self, node_entropy: Arc<NodeEntropy>) -> Result<Arc<Node>, BuildError> {
Expand DownExpand Up@@ -1361,8 +1404,8 @@ fn build_with_store_internal(
gossip_source_config: Option<&GossipSourceConfig>,
liquidity_source_config: Option<&LiquiditySourceConfig>,
pathfinding_scores_sync_config: Option<&PathfindingScoresSyncConfig>,
async_payments_role: Option<AsyncPaymentsRole>, seed_bytes: [u8; 64], runtime: Arc<Runtime>,
logger: Arc<Logger>, kv_store: Arc<DynStore>,
probing_config: Option<&ProbingConfig>, async_payments_role: Option<AsyncPaymentsRole>,
seed_bytes: [u8; 64], runtime: Arc<Runtime>, logger: Arc<Logger>, kv_store: Arc<DynStore>,
) -> Result<Node, BuildError> {
optionally_install_rustls_cryptoprovider();

Expand DownExpand Up@@ -2219,6 +2262,51 @@ fn build_with_store_internal(
_leak_checker.0.push(Arc::downgrade(&wallet) as Weak<dyn Any + Send + Sync>);
}

let prober = probing_config.map(|probing_cfg| {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Would be better to move this up before the leak checker setup.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

moved

let strategy: Arc<dyn ProbingStrategy> = match &probing_cfg.kind {
ProbingStrategyKind::HighDegree { top_node_count } => {
// Dedicated router for probing so the diversity penalty doesn't interfere
// with real payments; shares the scorer so probe results still train it.
let mut probing_fee_params = ProbabilisticScoringFeeParameters::default();
Comment thread
randomlogin marked this conversation as resolved.
if let Some(penalty) = probing_cfg.diversity_penalty_msat {
probing_fee_params.probing_diversity_penalty_msat = penalty;
}
let probing_router = Arc::new(DefaultRouter::new(
Arc::clone(&network_graph),
Arc::clone(&logger),
Arc::clone(&keys_manager),
Arc::clone(&scorer),
probing_fee_params,
));
Arc::new(HighDegreeStrategy::new(
Arc::clone(&network_graph),
Arc::clone(&channel_manager),
probing_router,
*top_node_count,
DEFAULT_MIN_PROBE_AMOUNT_MSAT,
DEFAULT_MAX_PROBE_AMOUNT_MSAT,
probing_cfg.cooldown,
config.probing_liquidity_limit_multiplier,
))
},
ProbingStrategyKind::RandomWalk { max_hops } => Arc::new(RandomWalkStrategy::new(
Arc::clone(&network_graph),
Arc::clone(&channel_manager),
*max_hops,
DEFAULT_MIN_PROBE_AMOUNT_MSAT,
DEFAULT_MAX_PROBE_AMOUNT_MSAT,
)),
ProbingStrategyKind::Custom(s) => Arc::clone(s),
};
Arc::new(Prober {
channel_manager: Arc::clone(&channel_manager),
logger: Arc::clone(&logger),
strategy,
interval: probing_cfg.interval,
max_locked_msat: probing_cfg.max_locked_msat,
})
});

Ok(Node {
runtime,
stop_sender,
Expand DownExpand Up@@ -2252,6 +2340,7 @@ fn build_with_store_internal(
om_mailbox,
async_payments_role,
hrn_resolver,
prober,
#[cfg(cycle_tests)]
_leak_checker,
})
Expand Down
6 changes: 6 additions & 0 deletions src/config.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,6 +28,12 @@ const DEFAULT_BDK_WALLET_SYNC_INTERVAL_SECS: u64 = 80;
const DEFAULT_LDK_WALLET_SYNC_INTERVAL_SECS: u64 = 30;
const DEFAULT_FEE_RATE_CACHE_UPDATE_INTERVAL_SECS: u64 = 60 * 10;
const DEFAULT_PROBING_LIQUIDITY_LIMIT_MULTIPLIER: u64 = 3;
pub(crate) const DEFAULT_PROBING_INTERVAL_SECS: u64 = 10;
pub(crate) const MIN_PROBING_INTERVAL: Duration = Duration::from_millis(100);
pub(crate) const DEFAULT_PROBED_NODE_COOLDOWN_SECS: u64 = 60 * 60; // 1 hour
pub(crate) const DEFAULT_MAX_PROBE_LOCKED_MSAT: u64 = 100_000_000; // 100k sats
pub(crate) const DEFAULT_MIN_PROBE_AMOUNT_MSAT: u64 = 1_000_000; // 1k sats
pub(crate) const DEFAULT_MAX_PROBE_AMOUNT_MSAT: u64 = 10_000_000; // 10k sats
const DEFAULT_ANCHOR_PER_CHANNEL_RESERVE_SATS: u64 = 25_000;

// The default timeout after which we abort a wallet syncing operation.
Expand Down
31 changes: 21 additions & 10 deletions src/event.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -52,6 +52,7 @@ use crate::payment::store::{
PaymentDetails, PaymentDetailsUpdate, PaymentDirection, PaymentKind, PaymentStatus,
};
use crate::payment::PaymentMetadata;
use crate::probing::Prober;
use crate::runtime::Runtime;
use crate::types::{
CustomTlvRecord, DynStore, KeysManager, OnionMessenger, PaymentStore, Sweeper, Wallet,
Expand DownExpand Up@@ -536,12 +537,13 @@ where
payment_store: Arc<PaymentStore>,
peer_store: Arc<PeerStore<L>>,
keys_manager: Arc<KeysManager>,
runtime: Arc<Runtime>,
logger: L,
config: Arc<Config>,
static_invoice_store: Option<StaticInvoiceStore>,
onion_messenger: Arc<OnionMessenger>,
om_mailbox: Option<Arc<OnionMessageMailbox>>,
prober: Option<Arc<Prober>>,
runtime: Arc<Runtime>,
logger: L,
config: Arc<Config>,
}

impl<L: Deref + Clone + Sync + Send + 'static> EventHandler<L>
Expand All@@ -556,8 +558,8 @@ where
liquidity_source: Arc<LiquiditySource<Arc<Logger>>>, payment_store: Arc<PaymentStore>,
peer_store: Arc<PeerStore<L>>, keys_manager: Arc<KeysManager>,
static_invoice_store: Option<StaticInvoiceStore>, onion_messenger: Arc<OnionMessenger>,
om_mailbox: Option<Arc<OnionMessageMailbox>>, runtime: Arc<Runtime>, logger: L,
config: Arc<Config>,
om_mailbox: Option<Arc<OnionMessageMailbox>>, prober: Option<Arc<Prober>>,
runtime: Arc<Runtime>, logger: L, config: Arc<Config>,
) -> Self {
Self {
event_queue,
Expand All@@ -571,12 +573,13 @@ where
payment_store,
peer_store,
keys_manager,
logger,
runtime,
config,
static_invoice_store,
onion_messenger,
om_mailbox,
prober,
runtime,
logger,
config,
}
}

Expand DownExpand Up@@ -1208,8 +1211,16 @@ where

LdkEvent::PaymentPathSuccessful { .. } => {},
LdkEvent::PaymentPathFailed { .. } => {},
LdkEvent::ProbeSuccessful { .. } => {},
LdkEvent::ProbeFailed { .. } => {},
LdkEvent::ProbeSuccessful { path, payment_id, .. } => {
if let Some(prober) = &self.prober {
prober.handle_background_probe_successful(&path, payment_id);
}
},
LdkEvent::ProbeFailed { path, payment_id, .. } => {
if let Some(prober) = &self.prober {
prober.handle_background_probe_failed(&path, payment_id);
}
},
LdkEvent::HTLCHandlingFailed { failure_type, .. } => {
self.liquidity_source
.lsps2_service()
Expand Down
1 change: 1 addition & 0 deletions src/ffi/types.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -149,6 +149,7 @@ pub use crate::entropy::{generate_entropy_mnemonic, NodeEntropy, WordCount};
use crate::error::Error;
pub use crate::liquidity::LSPS1OrderStatus;
pub use crate::logger::{LogLevel, LogRecord, LogWriter};
pub use crate::probing::ProbingConfig;
use crate::{hex_utils, SocketAddress, UserChannelId};

uniffi::custom_type!(PublicKey, String, {
Expand Down
19 changes: 19 additions & 0 deletions src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -101,10 +101,12 @@ pub mod logger;
mod message_handler;
pub mod payment;
mod peer_store;
pub mod probing;
mod runtime;
mod scoring;
mod tx_broadcaster;
mod types;
mod util;
mod wallet;

use std::default::Default;
Expand DownExpand Up@@ -172,6 +174,9 @@ use payment::{
UnifiedPayment,
};
use peer_store::{PeerInfo, PeerStore};
#[cfg(feature = "uniffi")]
pub use probing::ArcedProbingConfigBuilder as ProbingConfigBuilder;
use probing::{run_prober, Prober};
use runtime::Runtime;
pub use tokio;
use types::{
Expand DownExpand Up@@ -250,6 +255,7 @@ pub struct Node {
om_mailbox: Option<Arc<OnionMessageMailbox>>,
async_payments_role: Option<AsyncPaymentsRole>,
hrn_resolver: HRNResolver,
prober: Option<Arc<Prober>>,
#[cfg(cycle_tests)]
_leak_checker: LeakChecker,
}
Expand DownExpand Up@@ -610,11 +616,19 @@ impl Node {
static_invoice_store,
Arc::clone(&self.onion_messenger),
self.om_mailbox.clone(),
self.prober.clone(),
Arc::clone(&self.runtime),
Arc::clone(&self.logger),
Arc::clone(&self.config),
));

if let Some(prober) = self.prober.clone() {
let stop_rx = self.stop_sender.subscribe();
self.runtime.spawn_cancellable_background_task(async move {
run_prober(prober, stop_rx).await;
});
}

// Setup background processing
let background_persister = Arc::clone(&self.kv_store);
let background_event_handler = Arc::clone(&event_handler);
Expand DownExpand Up@@ -1145,6 +1159,11 @@ impl Node {
))
}

/// Returns a reference to the [`Prober`], or `None` if no probing strategy is configured.
pub fn prober(&self) -> Option<&Prober> {
self.prober.as_deref()
}

/// Retrieve a list of known channels.
pub fn list_channels(&self) -> Vec<ChannelDetails> {
self.channel_manager
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions bindings/ldk_node.udl
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,6 +13,8 @@ typedef dictionary TorConfig;

typedef interface NodeEntropy;

typedef interface ProbingConfig;

typedef enum WordCount;

[Remote]
Expand All@@ -32,6 +34,18 @@ interface LogWriter {
void log(LogRecord record);
};

interface ProbingConfigBuilder {
[Name=high_degree]
constructor(u64 top_node_count);
[Name=random_walk]
constructor(u64 max_hops);
void set_interval(u64 secs);
void set_max_locked_msat(u64 max_msat);
void set_diversity_penalty_msat(u64 penalty_msat);
void set_cooldown(u64 secs);
ProbingConfig build();
};

interface Builder {
constructor();
[Name=from_config]
Expand DownExpand Up@@ -59,6 +73,7 @@ interface Builder {
void set_node_alias(string node_alias);
[Throws=BuildError]
void set_async_payments_role(AsyncPaymentsRole? role);
void set_probing_config(ProbingConfig config);
[Throws=BuildError]
Node build(NodeEntropy node_entropy);
[Throws=BuildError]
Expand Down
93 changes: 91 additions & 2 deletions src/builder.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -50,6 +50,7 @@ use crate::config::{
default_user_config, may_announce_channel, AnnounceError, AsyncPaymentsRole,
BitcoindRestClientConfig, Config, ElectrumSyncConfig, EsploraSyncConfig, HRNResolverConfig,
TorConfig, DEFAULT_ESPLORA_SERVER_URL, DEFAULT_LOG_FILENAME, DEFAULT_LOG_LEVEL,
DEFAULT_MAX_PROBE_AMOUNT_MSAT, DEFAULT_MIN_PROBE_AMOUNT_MSAT,
};
use crate::connection::ConnectionManager;
use crate::entropy::NodeEntropy;
Expand All@@ -74,6 +75,10 @@ use crate::logger::{log_error, LdkLogger, LogLevel, LogWriter, Logger};
use crate::message_handler::NodeCustomMessageHandler;
use crate::payment::asynchronous::om_mailbox::OnionMessageMailbox;
use crate::peer_store::PeerStore;
use crate::probing::{
HighDegreeStrategy, Prober, ProbingConfig, ProbingStrategy, ProbingStrategyKind,
RandomWalkStrategy,
};
use crate::runtime::{Runtime, RuntimeSpawner};
use crate::tx_broadcaster::TransactionBroadcaster;
use crate::types::{
Expand DownExpand Up@@ -306,6 +311,7 @@ pub struct NodeBuilder {
async_payments_role: Option<AsyncPaymentsRole>,
runtime_handle: Option<tokio::runtime::Handle>,
pathfinding_scores_sync_config: Option<PathfindingScoresSyncConfig>,
probing_config: Option<ProbingConfig>,
}

impl NodeBuilder {
Expand All@@ -323,6 +329,7 @@ impl NodeBuilder {
let log_writer_config = None;
let runtime_handle = None;
let pathfinding_scores_sync_config = None;
let probing_config = None;
Self {
config,
chain_data_source_config,
Expand All@@ -332,6 +339,7 @@ impl NodeBuilder {
runtime_handle,
async_payments_role: None,
pathfinding_scores_sync_config,
probing_config,
}
}

Expand DownExpand Up@@ -629,6 +637,31 @@ impl NodeBuilder {
Ok(self)
}

/// Sets background probing config.
///
/// Use [`ProbingConfigBuilder`] to build the configuration:
/// ```no_run
/// # #[cfg(not(feature = "uniffi"))]
/// # {
/// use std::time::Duration;
/// use ldk_node::Builder;
/// use ldk_node::probing::ProbingConfigBuilder;
///
/// let mut builder = Builder::new();
/// builder.set_probing_config(
/// ProbingConfigBuilder::high_degree(100)
/// .interval(Duration::from_secs(30))
/// .build()
/// );
/// # }
/// ```
///
/// [`ProbingConfigBuilder`]: crate::probing::ProbingConfigBuilder
pub fn set_probing_config(&mut self, config: ProbingConfig) -> &mut Self {
self.probing_config = Some(config);
self
}

/// Builds a [`Node`] instance with a [`SqliteStore`] backend and according to the options
/// previously configured.
pub fn build(&self, node_entropy: NodeEntropy) -> Result<Node, BuildError> {
Expand DownExpand Up@@ -868,6 +901,7 @@ impl NodeBuilder {
self.gossip_source_config.as_ref(),
self.liquidity_source_config.as_ref(),
self.pathfinding_scores_sync_config.as_ref(),
self.probing_config.as_ref(),
self.async_payments_role,
seed_bytes,
runtime,
Expand DownExpand Up@@ -1166,6 +1200,15 @@ impl ArcedNodeBuilder {
self.inner.write().expect("lock").set_async_payments_role(role).map(|_| ())
}

/// Configures background probing.
///
/// Use [`ProbingConfigBuilder`] to build the configuration.
///
/// [`ProbingConfigBuilder`]: crate::probing::ProbingConfigBuilder
pub fn set_probing_config(&self, config: Arc<ProbingConfig>) {
self.inner.write().expect("lock").set_probing_config((*config).clone());
}

/// Builds a [`Node`] instance with a [`SqliteStore`] backend and according to the options
/// previously configured.
pub fn build(&self, node_entropy: Arc<NodeEntropy>) -> Result<Arc<Node>, BuildError> {
Expand DownExpand Up@@ -1361,8 +1404,8 @@ fn build_with_store_internal(
gossip_source_config: Option<&GossipSourceConfig>,
liquidity_source_config: Option<&LiquiditySourceConfig>,
pathfinding_scores_sync_config: Option<&PathfindingScoresSyncConfig>,
async_payments_role: Option<AsyncPaymentsRole>, seed_bytes: [u8; 64], runtime: Arc<Runtime>,
logger: Arc<Logger>, kv_store: Arc<DynStore>,
probing_config: Option<&ProbingConfig>, async_payments_role: Option<AsyncPaymentsRole>,
seed_bytes: [u8; 64], runtime: Arc<Runtime>, logger: Arc<Logger>, kv_store: Arc<DynStore>,
) -> Result<Node, BuildError> {
optionally_install_rustls_cryptoprovider();

Expand DownExpand Up@@ -2219,6 +2262,51 @@ fn build_with_store_internal(
_leak_checker.0.push(Arc::downgrade(&wallet) as Weak<dyn Any + Send + Sync>);
}

let prober = probing_config.map(|probing_cfg| {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Would be better to move this up before the leak checker setup.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

moved

let strategy: Arc<dyn ProbingStrategy> = match &probing_cfg.kind {
ProbingStrategyKind::HighDegree { top_node_count } => {
// Dedicated router for probing so the diversity penalty doesn't interfere
// with real payments; shares the scorer so probe results still train it.
let mut probing_fee_params = ProbabilisticScoringFeeParameters::default();
Comment thread
randomlogin marked this conversation as resolved.
if let Some(penalty) = probing_cfg.diversity_penalty_msat {
probing_fee_params.probing_diversity_penalty_msat = penalty;
}
let probing_router = Arc::new(DefaultRouter::new(
Arc::clone(&network_graph),
Arc::clone(&logger),
Arc::clone(&keys_manager),
Arc::clone(&scorer),
probing_fee_params,
));
Arc::new(HighDegreeStrategy::new(
Arc::clone(&network_graph),
Arc::clone(&channel_manager),
probing_router,
*top_node_count,
DEFAULT_MIN_PROBE_AMOUNT_MSAT,
DEFAULT_MAX_PROBE_AMOUNT_MSAT,
probing_cfg.cooldown,
config.probing_liquidity_limit_multiplier,
))
},
ProbingStrategyKind::RandomWalk { max_hops } => Arc::new(RandomWalkStrategy::new(
Arc::clone(&network_graph),
Arc::clone(&channel_manager),
*max_hops,
DEFAULT_MIN_PROBE_AMOUNT_MSAT,
DEFAULT_MAX_PROBE_AMOUNT_MSAT,
)),
ProbingStrategyKind::Custom(s) => Arc::clone(s),
};
Arc::new(Prober {
channel_manager: Arc::clone(&channel_manager),
logger: Arc::clone(&logger),
strategy,
interval: probing_cfg.interval,
max_locked_msat: probing_cfg.max_locked_msat,
})
});

Ok(Node {
runtime,
stop_sender,
Expand DownExpand Up@@ -2252,6 +2340,7 @@ fn build_with_store_internal(
om_mailbox,
async_payments_role,
hrn_resolver,
prober,
#[cfg(cycle_tests)]
_leak_checker,
})
Expand Down
6 changes: 6 additions & 0 deletions src/config.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,6 +28,12 @@ const DEFAULT_BDK_WALLET_SYNC_INTERVAL_SECS: u64 = 80;
const DEFAULT_LDK_WALLET_SYNC_INTERVAL_SECS: u64 = 30;
const DEFAULT_FEE_RATE_CACHE_UPDATE_INTERVAL_SECS: u64 = 60 * 10;
const DEFAULT_PROBING_LIQUIDITY_LIMIT_MULTIPLIER: u64 = 3;
pub(crate) const DEFAULT_PROBING_INTERVAL_SECS: u64 = 10;
pub(crate) const MIN_PROBING_INTERVAL: Duration = Duration::from_millis(100);
pub(crate) const DEFAULT_PROBED_NODE_COOLDOWN_SECS: u64 = 60 * 60; // 1 hour
pub(crate) const DEFAULT_MAX_PROBE_LOCKED_MSAT: u64 = 100_000_000; // 100k sats
pub(crate) const DEFAULT_MIN_PROBE_AMOUNT_MSAT: u64 = 1_000_000; // 1k sats
pub(crate) const DEFAULT_MAX_PROBE_AMOUNT_MSAT: u64 = 10_000_000; // 10k sats
const DEFAULT_ANCHOR_PER_CHANNEL_RESERVE_SATS: u64 = 25_000;

// The default timeout after which we abort a wallet syncing operation.
Expand Down
31 changes: 21 additions & 10 deletions src/event.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -52,6 +52,7 @@ use crate::payment::store::{
PaymentDetails, PaymentDetailsUpdate, PaymentDirection, PaymentKind, PaymentStatus,
};
use crate::payment::PaymentMetadata;
use crate::probing::Prober;
use crate::runtime::Runtime;
use crate::types::{
CustomTlvRecord, DynStore, KeysManager, OnionMessenger, PaymentStore, Sweeper, Wallet,
Expand DownExpand Up@@ -536,12 +537,13 @@ where
payment_store: Arc<PaymentStore>,
peer_store: Arc<PeerStore<L>>,
keys_manager: Arc<KeysManager>,
runtime: Arc<Runtime>,
logger: L,
config: Arc<Config>,
static_invoice_store: Option<StaticInvoiceStore>,
onion_messenger: Arc<OnionMessenger>,
om_mailbox: Option<Arc<OnionMessageMailbox>>,
prober: Option<Arc<Prober>>,
runtime: Arc<Runtime>,
logger: L,
config: Arc<Config>,
}

impl<L: Deref + Clone + Sync + Send + 'static> EventHandler<L>
Expand All@@ -556,8 +558,8 @@ where
liquidity_source: Arc<LiquiditySource<Arc<Logger>>>, payment_store: Arc<PaymentStore>,
peer_store: Arc<PeerStore<L>>, keys_manager: Arc<KeysManager>,
static_invoice_store: Option<StaticInvoiceStore>, onion_messenger: Arc<OnionMessenger>,
om_mailbox: Option<Arc<OnionMessageMailbox>>, runtime: Arc<Runtime>, logger: L,
config: Arc<Config>,
om_mailbox: Option<Arc<OnionMessageMailbox>>, prober: Option<Arc<Prober>>,
runtime: Arc<Runtime>, logger: L, config: Arc<Config>,
) -> Self {
Self {
event_queue,
Expand All@@ -571,12 +573,13 @@ where
payment_store,
peer_store,
keys_manager,
logger,
runtime,
config,
static_invoice_store,
onion_messenger,
om_mailbox,
prober,
runtime,
logger,
config,
}
}

Expand DownExpand Up@@ -1208,8 +1211,16 @@ where

LdkEvent::PaymentPathSuccessful { .. } => {},
LdkEvent::PaymentPathFailed { .. } => {},
LdkEvent::ProbeSuccessful { .. } => {},
LdkEvent::ProbeFailed { .. } => {},
LdkEvent::ProbeSuccessful { path, payment_id, .. } => {
if let Some(prober) = &self.prober {
prober.handle_background_probe_successful(&path, payment_id);
}
},
LdkEvent::ProbeFailed { path, payment_id, .. } => {
if let Some(prober) = &self.prober {
prober.handle_background_probe_failed(&path, payment_id);
}
},
LdkEvent::HTLCHandlingFailed { failure_type, .. } => {
self.liquidity_source
.lsps2_service()
Expand Down
1 change: 1 addition & 0 deletions src/ffi/types.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -149,6 +149,7 @@ pub use crate::entropy::{generate_entropy_mnemonic, NodeEntropy, WordCount};
use crate::error::Error;
pub use crate::liquidity::LSPS1OrderStatus;
pub use crate::logger::{LogLevel, LogRecord, LogWriter};
pub use crate::probing::ProbingConfig;
use crate::{hex_utils, SocketAddress, UserChannelId};

uniffi::custom_type!(PublicKey, String, {
Expand Down
19 changes: 19 additions & 0 deletions src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -101,10 +101,12 @@ pub mod logger;
mod message_handler;
pub mod payment;
mod peer_store;
pub mod probing;
mod runtime;
mod scoring;
mod tx_broadcaster;
mod types;
mod util;
mod wallet;

use std::default::Default;
Expand DownExpand Up@@ -172,6 +174,9 @@ use payment::{
UnifiedPayment,
};
use peer_store::{PeerInfo, PeerStore};
#[cfg(feature = "uniffi")]
pub use probing::ArcedProbingConfigBuilder as ProbingConfigBuilder;
use probing::{run_prober, Prober};
use runtime::Runtime;
pub use tokio;
use types::{
Expand DownExpand Up@@ -250,6 +255,7 @@ pub struct Node {
om_mailbox: Option<Arc<OnionMessageMailbox>>,
async_payments_role: Option<AsyncPaymentsRole>,
hrn_resolver: HRNResolver,
prober: Option<Arc<Prober>>,
#[cfg(cycle_tests)]
_leak_checker: LeakChecker,
}
Expand DownExpand Up@@ -610,11 +616,19 @@ impl Node {
static_invoice_store,
Arc::clone(&self.onion_messenger),
self.om_mailbox.clone(),
self.prober.clone(),
Arc::clone(&self.runtime),
Arc::clone(&self.logger),
Arc::clone(&self.config),
));

if let Some(prober) = self.prober.clone() {
let stop_rx = self.stop_sender.subscribe();
self.runtime.spawn_cancellable_background_task(async move {
run_prober(prober, stop_rx).await;
});
}

// Setup background processing
let background_persister = Arc::clone(&self.kv_store);
let background_event_handler = Arc::clone(&event_handler);
Expand DownExpand Up@@ -1145,6 +1159,11 @@ impl Node {
))
}

/// Returns a reference to the [`Prober`], or `None` if no probing strategy is configured.
pub fn prober(&self) -> Option<&Prober> {
self.prober.as_deref()
}

/// Retrieve a list of known channels.
pub fn list_channels(&self) -> Vec<ChannelDetails> {
self.channel_manager
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions bindings/ldk_node.udl
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,6 +13,8 @@ typedef dictionary TorConfig;

typedef interface NodeEntropy;

typedef interface ProbingConfig;

typedef enum WordCount;

[Remote]
Expand All@@ -32,6 +34,18 @@ interface LogWriter {
void log(LogRecord record);
};

interface ProbingConfigBuilder {
[Name=high_degree]
constructor(u64 top_node_count);
[Name=random_walk]
constructor(u64 max_hops);
void set_interval(u64 secs);
void set_max_locked_msat(u64 max_msat);
void set_diversity_penalty_msat(u64 penalty_msat);
void set_cooldown(u64 secs);
ProbingConfig build();
};

interface Builder {
constructor();
[Name=from_config]
Expand DownExpand Up@@ -59,6 +73,7 @@ interface Builder {
void set_node_alias(string node_alias);
[Throws=BuildError]
void set_async_payments_role(AsyncPaymentsRole? role);
void set_probing_config(ProbingConfig config);
[Throws=BuildError]
Node build(NodeEntropy node_entropy);
[Throws=BuildError]
Expand Down
93 changes: 91 additions & 2 deletions src/builder.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -50,6 +50,7 @@ use crate::config::{
default_user_config, may_announce_channel, AnnounceError, AsyncPaymentsRole,
BitcoindRestClientConfig, Config, ElectrumSyncConfig, EsploraSyncConfig, HRNResolverConfig,
TorConfig, DEFAULT_ESPLORA_SERVER_URL, DEFAULT_LOG_FILENAME, DEFAULT_LOG_LEVEL,
DEFAULT_MAX_PROBE_AMOUNT_MSAT, DEFAULT_MIN_PROBE_AMOUNT_MSAT,
};
use crate::connection::ConnectionManager;
use crate::entropy::NodeEntropy;
Expand All@@ -74,6 +75,10 @@ use crate::logger::{log_error, LdkLogger, LogLevel, LogWriter, Logger};
use crate::message_handler::NodeCustomMessageHandler;
use crate::payment::asynchronous::om_mailbox::OnionMessageMailbox;
use crate::peer_store::PeerStore;
use crate::probing::{
HighDegreeStrategy, Prober, ProbingConfig, ProbingStrategy, ProbingStrategyKind,
RandomWalkStrategy,
};
use crate::runtime::{Runtime, RuntimeSpawner};
use crate::tx_broadcaster::TransactionBroadcaster;
use crate::types::{
Expand DownExpand Up@@ -306,6 +311,7 @@ pub struct NodeBuilder {
async_payments_role: Option<AsyncPaymentsRole>,
runtime_handle: Option<tokio::runtime::Handle>,
pathfinding_scores_sync_config: Option<PathfindingScoresSyncConfig>,
probing_config: Option<ProbingConfig>,
}

impl NodeBuilder {
Expand All@@ -323,6 +329,7 @@ impl NodeBuilder {
let log_writer_config = None;
let runtime_handle = None;
let pathfinding_scores_sync_config = None;
let probing_config = None;
Self {
config,
chain_data_source_config,
Expand All@@ -332,6 +339,7 @@ impl NodeBuilder {
runtime_handle,
async_payments_role: None,
pathfinding_scores_sync_config,
probing_config,
}
}

Expand DownExpand Up@@ -629,6 +637,31 @@ impl NodeBuilder {
Ok(self)
}

/// Sets background probing config.
///
/// Use [`ProbingConfigBuilder`] to build the configuration:
/// ```no_run
/// # #[cfg(not(feature = "uniffi"))]
/// # {
/// use std::time::Duration;
/// use ldk_node::Builder;
/// use ldk_node::probing::ProbingConfigBuilder;
///
/// let mut builder = Builder::new();
/// builder.set_probing_config(
/// ProbingConfigBuilder::high_degree(100)
/// .interval(Duration::from_secs(30))
/// .build()
/// );
/// # }
/// ```
///
/// [`ProbingConfigBuilder`]: crate::probing::ProbingConfigBuilder
pub fn set_probing_config(&mut self, config: ProbingConfig) -> &mut Self {
self.probing_config = Some(config);
self
}

/// Builds a [`Node`] instance with a [`SqliteStore`] backend and according to the options
/// previously configured.
pub fn build(&self, node_entropy: NodeEntropy) -> Result<Node, BuildError> {
Expand DownExpand Up@@ -868,6 +901,7 @@ impl NodeBuilder {
self.gossip_source_config.as_ref(),
self.liquidity_source_config.as_ref(),
self.pathfinding_scores_sync_config.as_ref(),
self.probing_config.as_ref(),
self.async_payments_role,
seed_bytes,
runtime,
Expand DownExpand Up@@ -1166,6 +1200,15 @@ impl ArcedNodeBuilder {
self.inner.write().expect("lock").set_async_payments_role(role).map(|_| ())
}

/// Configures background probing.
///
/// Use [`ProbingConfigBuilder`] to build the configuration.
///
/// [`ProbingConfigBuilder`]: crate::probing::ProbingConfigBuilder
pub fn set_probing_config(&self, config: Arc<ProbingConfig>) {
self.inner.write().expect("lock").set_probing_config((*config).clone());
}

/// Builds a [`Node`] instance with a [`SqliteStore`] backend and according to the options
/// previously configured.
pub fn build(&self, node_entropy: Arc<NodeEntropy>) -> Result<Arc<Node>, BuildError> {
Expand DownExpand Up@@ -1361,8 +1404,8 @@ fn build_with_store_internal(
gossip_source_config: Option<&GossipSourceConfig>,
liquidity_source_config: Option<&LiquiditySourceConfig>,
pathfinding_scores_sync_config: Option<&PathfindingScoresSyncConfig>,
async_payments_role: Option<AsyncPaymentsRole>, seed_bytes: [u8; 64], runtime: Arc<Runtime>,
logger: Arc<Logger>, kv_store: Arc<DynStore>,
probing_config: Option<&ProbingConfig>, async_payments_role: Option<AsyncPaymentsRole>,
seed_bytes: [u8; 64], runtime: Arc<Runtime>, logger: Arc<Logger>, kv_store: Arc<DynStore>,
) -> Result<Node, BuildError> {
optionally_install_rustls_cryptoprovider();

Expand DownExpand Up@@ -2219,6 +2262,51 @@ fn build_with_store_internal(
_leak_checker.0.push(Arc::downgrade(&wallet) as Weak<dyn Any + Send + Sync>);
}

let prober = probing_config.map(|probing_cfg| {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Would be better to move this up before the leak checker setup.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

moved

let strategy: Arc<dyn ProbingStrategy> = match &probing_cfg.kind {
ProbingStrategyKind::HighDegree { top_node_count } => {
// Dedicated router for probing so the diversity penalty doesn't interfere
// with real payments; shares the scorer so probe results still train it.
let mut probing_fee_params = ProbabilisticScoringFeeParameters::default();
Comment thread
randomlogin marked this conversation as resolved.
if let Some(penalty) = probing_cfg.diversity_penalty_msat {
probing_fee_params.probing_diversity_penalty_msat = penalty;
}
let probing_router = Arc::new(DefaultRouter::new(
Arc::clone(&network_graph),
Arc::clone(&logger),
Arc::clone(&keys_manager),
Arc::clone(&scorer),
probing_fee_params,
));
Arc::new(HighDegreeStrategy::new(
Arc::clone(&network_graph),
Arc::clone(&channel_manager),
probing_router,
*top_node_count,
DEFAULT_MIN_PROBE_AMOUNT_MSAT,
DEFAULT_MAX_PROBE_AMOUNT_MSAT,
probing_cfg.cooldown,
config.probing_liquidity_limit_multiplier,
))
},
ProbingStrategyKind::RandomWalk { max_hops } => Arc::new(RandomWalkStrategy::new(
Arc::clone(&network_graph),
Arc::clone(&channel_manager),
*max_hops,
DEFAULT_MIN_PROBE_AMOUNT_MSAT,
DEFAULT_MAX_PROBE_AMOUNT_MSAT,
)),
ProbingStrategyKind::Custom(s) => Arc::clone(s),
};
Arc::new(Prober {
channel_manager: Arc::clone(&channel_manager),
logger: Arc::clone(&logger),
strategy,
interval: probing_cfg.interval,
max_locked_msat: probing_cfg.max_locked_msat,
})
});

Ok(Node {
runtime,
stop_sender,
Expand DownExpand Up@@ -2252,6 +2340,7 @@ fn build_with_store_internal(
om_mailbox,
async_payments_role,
hrn_resolver,
prober,
#[cfg(cycle_tests)]
_leak_checker,
})
Expand Down
6 changes: 6 additions & 0 deletions src/config.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,6 +28,12 @@ const DEFAULT_BDK_WALLET_SYNC_INTERVAL_SECS: u64 = 80;
const DEFAULT_LDK_WALLET_SYNC_INTERVAL_SECS: u64 = 30;
const DEFAULT_FEE_RATE_CACHE_UPDATE_INTERVAL_SECS: u64 = 60 * 10;
const DEFAULT_PROBING_LIQUIDITY_LIMIT_MULTIPLIER: u64 = 3;
pub(crate) const DEFAULT_PROBING_INTERVAL_SECS: u64 = 10;
pub(crate) const MIN_PROBING_INTERVAL: Duration = Duration::from_millis(100);
pub(crate) const DEFAULT_PROBED_NODE_COOLDOWN_SECS: u64 = 60 * 60; // 1 hour
pub(crate) const DEFAULT_MAX_PROBE_LOCKED_MSAT: u64 = 100_000_000; // 100k sats
pub(crate) const DEFAULT_MIN_PROBE_AMOUNT_MSAT: u64 = 1_000_000; // 1k sats
pub(crate) const DEFAULT_MAX_PROBE_AMOUNT_MSAT: u64 = 10_000_000; // 10k sats
const DEFAULT_ANCHOR_PER_CHANNEL_RESERVE_SATS: u64 = 25_000;

// The default timeout after which we abort a wallet syncing operation.
Expand Down
31 changes: 21 additions & 10 deletions src/event.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -52,6 +52,7 @@ use crate::payment::store::{
PaymentDetails, PaymentDetailsUpdate, PaymentDirection, PaymentKind, PaymentStatus,
};
use crate::payment::PaymentMetadata;
use crate::probing::Prober;
use crate::runtime::Runtime;
use crate::types::{
CustomTlvRecord, DynStore, KeysManager, OnionMessenger, PaymentStore, Sweeper, Wallet,
Expand DownExpand Up@@ -536,12 +537,13 @@ where
payment_store: Arc<PaymentStore>,
peer_store: Arc<PeerStore<L>>,
keys_manager: Arc<KeysManager>,
runtime: Arc<Runtime>,
logger: L,
config: Arc<Config>,
static_invoice_store: Option<StaticInvoiceStore>,
onion_messenger: Arc<OnionMessenger>,
om_mailbox: Option<Arc<OnionMessageMailbox>>,
prober: Option<Arc<Prober>>,
runtime: Arc<Runtime>,
logger: L,
config: Arc<Config>,
}

impl<L: Deref + Clone + Sync + Send + 'static> EventHandler<L>
Expand All@@ -556,8 +558,8 @@ where
liquidity_source: Arc<LiquiditySource<Arc<Logger>>>, payment_store: Arc<PaymentStore>,
peer_store: Arc<PeerStore<L>>, keys_manager: Arc<KeysManager>,
static_invoice_store: Option<StaticInvoiceStore>, onion_messenger: Arc<OnionMessenger>,
om_mailbox: Option<Arc<OnionMessageMailbox>>, runtime: Arc<Runtime>, logger: L,
config: Arc<Config>,
om_mailbox: Option<Arc<OnionMessageMailbox>>, prober: Option<Arc<Prober>>,
runtime: Arc<Runtime>, logger: L, config: Arc<Config>,
) -> Self {
Self {
event_queue,
Expand All@@ -571,12 +573,13 @@ where
payment_store,
peer_store,
keys_manager,
logger,
runtime,
config,
static_invoice_store,
onion_messenger,
om_mailbox,
prober,
runtime,
logger,
config,
}
}

Expand DownExpand Up@@ -1208,8 +1211,16 @@ where

LdkEvent::PaymentPathSuccessful { .. } => {},
LdkEvent::PaymentPathFailed { .. } => {},
LdkEvent::ProbeSuccessful { .. } => {},
LdkEvent::ProbeFailed { .. } => {},
LdkEvent::ProbeSuccessful { path, payment_id, .. } => {
if let Some(prober) = &self.prober {
prober.handle_background_probe_successful(&path, payment_id);
}
},
LdkEvent::ProbeFailed { path, payment_id, .. } => {
if let Some(prober) = &self.prober {
prober.handle_background_probe_failed(&path, payment_id);
}
},
LdkEvent::HTLCHandlingFailed { failure_type, .. } => {
self.liquidity_source
.lsps2_service()
Expand Down
1 change: 1 addition & 0 deletions src/ffi/types.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -149,6 +149,7 @@ pub use crate::entropy::{generate_entropy_mnemonic, NodeEntropy, WordCount};
use crate::error::Error;
pub use crate::liquidity::LSPS1OrderStatus;
pub use crate::logger::{LogLevel, LogRecord, LogWriter};
pub use crate::probing::ProbingConfig;
use crate::{hex_utils, SocketAddress, UserChannelId};

uniffi::custom_type!(PublicKey, String, {
Expand Down
19 changes: 19 additions & 0 deletions src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -101,10 +101,12 @@ pub mod logger;
mod message_handler;
pub mod payment;
mod peer_store;
pub mod probing;
mod runtime;
mod scoring;
mod tx_broadcaster;
mod types;
mod util;
mod wallet;

use std::default::Default;
Expand DownExpand Up@@ -172,6 +174,9 @@ use payment::{
UnifiedPayment,
};
use peer_store::{PeerInfo, PeerStore};
#[cfg(feature = "uniffi")]
pub use probing::ArcedProbingConfigBuilder as ProbingConfigBuilder;
use probing::{run_prober, Prober};
use runtime::Runtime;
pub use tokio;
use types::{
Expand DownExpand Up@@ -250,6 +255,7 @@ pub struct Node {
om_mailbox: Option<Arc<OnionMessageMailbox>>,
async_payments_role: Option<AsyncPaymentsRole>,
hrn_resolver: HRNResolver,
prober: Option<Arc<Prober>>,
#[cfg(cycle_tests)]
_leak_checker: LeakChecker,
}
Expand DownExpand Up@@ -610,11 +616,19 @@ impl Node {
static_invoice_store,
Arc::clone(&self.onion_messenger),
self.om_mailbox.clone(),
self.prober.clone(),
Arc::clone(&self.runtime),
Arc::clone(&self.logger),
Arc::clone(&self.config),
));

if let Some(prober) = self.prober.clone() {
let stop_rx = self.stop_sender.subscribe();
self.runtime.spawn_cancellable_background_task(async move {
run_prober(prober, stop_rx).await;
});
}

// Setup background processing
let background_persister = Arc::clone(&self.kv_store);
let background_event_handler = Arc::clone(&event_handler);
Expand DownExpand Up@@ -1145,6 +1159,11 @@ impl Node {
))
}

/// Returns a reference to the [`Prober`], or `None` if no probing strategy is configured.
pub fn prober(&self) -> Option<&Prober> {
self.prober.as_deref()
}

/// Retrieve a list of known channels.
pub fn list_channels(&self) -> Vec<ChannelDetails> {
self.channel_manager
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions bindings/ldk_node.udl
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,6 +13,8 @@ typedef dictionary TorConfig;

typedef interface NodeEntropy;

typedef interface ProbingConfig;

typedef enum WordCount;

[Remote]
Expand All@@ -32,6 +34,18 @@ interface LogWriter {
void log(LogRecord record);
};

interface ProbingConfigBuilder {
[Name=high_degree]
constructor(u64 top_node_count);
[Name=random_walk]
constructor(u64 max_hops);
void set_interval(u64 secs);
void set_max_locked_msat(u64 max_msat);
void set_diversity_penalty_msat(u64 penalty_msat);
void set_cooldown(u64 secs);
ProbingConfig build();
};

interface Builder {
constructor();
[Name=from_config]
Expand DownExpand Up@@ -59,6 +73,7 @@ interface Builder {
void set_node_alias(string node_alias);
[Throws=BuildError]
void set_async_payments_role(AsyncPaymentsRole? role);
void set_probing_config(ProbingConfig config);
[Throws=BuildError]
Node build(NodeEntropy node_entropy);
[Throws=BuildError]
Expand Down
93 changes: 91 additions & 2 deletions src/builder.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -50,6 +50,7 @@ use crate::config::{
default_user_config, may_announce_channel, AnnounceError, AsyncPaymentsRole,
BitcoindRestClientConfig, Config, ElectrumSyncConfig, EsploraSyncConfig, HRNResolverConfig,
TorConfig, DEFAULT_ESPLORA_SERVER_URL, DEFAULT_LOG_FILENAME, DEFAULT_LOG_LEVEL,
DEFAULT_MAX_PROBE_AMOUNT_MSAT, DEFAULT_MIN_PROBE_AMOUNT_MSAT,
};
use crate::connection::ConnectionManager;
use crate::entropy::NodeEntropy;
Expand All@@ -74,6 +75,10 @@ use crate::logger::{log_error, LdkLogger, LogLevel, LogWriter, Logger};
use crate::message_handler::NodeCustomMessageHandler;
use crate::payment::asynchronous::om_mailbox::OnionMessageMailbox;
use crate::peer_store::PeerStore;
use crate::probing::{
HighDegreeStrategy, Prober, ProbingConfig, ProbingStrategy, ProbingStrategyKind,
RandomWalkStrategy,
};
use crate::runtime::{Runtime, RuntimeSpawner};
use crate::tx_broadcaster::TransactionBroadcaster;
use crate::types::{
Expand DownExpand Up@@ -306,6 +311,7 @@ pub struct NodeBuilder {
async_payments_role: Option<AsyncPaymentsRole>,
runtime_handle: Option<tokio::runtime::Handle>,
pathfinding_scores_sync_config: Option<PathfindingScoresSyncConfig>,
probing_config: Option<ProbingConfig>,
}

impl NodeBuilder {
Expand All@@ -323,6 +329,7 @@ impl NodeBuilder {
let log_writer_config = None;
let runtime_handle = None;
let pathfinding_scores_sync_config = None;
let probing_config = None;
Self {
config,
chain_data_source_config,
Expand All@@ -332,6 +339,7 @@ impl NodeBuilder {
runtime_handle,
async_payments_role: None,
pathfinding_scores_sync_config,
probing_config,
}
}

Expand DownExpand Up@@ -629,6 +637,31 @@ impl NodeBuilder {
Ok(self)
}

/// Sets background probing config.
///
/// Use [`ProbingConfigBuilder`] to build the configuration:
/// ```no_run
/// # #[cfg(not(feature = "uniffi"))]
/// # {
/// use std::time::Duration;
/// use ldk_node::Builder;
/// use ldk_node::probing::ProbingConfigBuilder;
///
/// let mut builder = Builder::new();
/// builder.set_probing_config(
/// ProbingConfigBuilder::high_degree(100)
/// .interval(Duration::from_secs(30))
/// .build()
/// );
/// # }
/// ```
///
/// [`ProbingConfigBuilder`]: crate::probing::ProbingConfigBuilder
pub fn set_probing_config(&mut self, config: ProbingConfig) -> &mut Self {
self.probing_config = Some(config);
self
}

/// Builds a [`Node`] instance with a [`SqliteStore`] backend and according to the options
/// previously configured.
pub fn build(&self, node_entropy: NodeEntropy) -> Result<Node, BuildError> {
Expand DownExpand Up@@ -868,6 +901,7 @@ impl NodeBuilder {
self.gossip_source_config.as_ref(),
self.liquidity_source_config.as_ref(),
self.pathfinding_scores_sync_config.as_ref(),
self.probing_config.as_ref(),
self.async_payments_role,
seed_bytes,
runtime,
Expand DownExpand Up@@ -1166,6 +1200,15 @@ impl ArcedNodeBuilder {
self.inner.write().expect("lock").set_async_payments_role(role).map(|_| ())
}

/// Configures background probing.
///
/// Use [`ProbingConfigBuilder`] to build the configuration.
///
/// [`ProbingConfigBuilder`]: crate::probing::ProbingConfigBuilder
pub fn set_probing_config(&self, config: Arc<ProbingConfig>) {
self.inner.write().expect("lock").set_probing_config((*config).clone());
}

/// Builds a [`Node`] instance with a [`SqliteStore`] backend and according to the options
/// previously configured.
pub fn build(&self, node_entropy: Arc<NodeEntropy>) -> Result<Arc<Node>, BuildError> {
Expand DownExpand Up@@ -1361,8 +1404,8 @@ fn build_with_store_internal(
gossip_source_config: Option<&GossipSourceConfig>,
liquidity_source_config: Option<&LiquiditySourceConfig>,
pathfinding_scores_sync_config: Option<&PathfindingScoresSyncConfig>,
async_payments_role: Option<AsyncPaymentsRole>, seed_bytes: [u8; 64], runtime: Arc<Runtime>,
logger: Arc<Logger>, kv_store: Arc<DynStore>,
probing_config: Option<&ProbingConfig>, async_payments_role: Option<AsyncPaymentsRole>,
seed_bytes: [u8; 64], runtime: Arc<Runtime>, logger: Arc<Logger>, kv_store: Arc<DynStore>,
) -> Result<Node, BuildError> {
optionally_install_rustls_cryptoprovider();

Expand DownExpand Up@@ -2219,6 +2262,51 @@ fn build_with_store_internal(
_leak_checker.0.push(Arc::downgrade(&wallet) as Weak<dyn Any + Send + Sync>);
}

let prober = probing_config.map(|probing_cfg| {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Would be better to move this up before the leak checker setup.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

moved

let strategy: Arc<dyn ProbingStrategy> = match &probing_cfg.kind {
ProbingStrategyKind::HighDegree { top_node_count } => {
// Dedicated router for probing so the diversity penalty doesn't interfere
// with real payments; shares the scorer so probe results still train it.
let mut probing_fee_params = ProbabilisticScoringFeeParameters::default();
Comment thread
randomlogin marked this conversation as resolved.
if let Some(penalty) = probing_cfg.diversity_penalty_msat {
probing_fee_params.probing_diversity_penalty_msat = penalty;
}
let probing_router = Arc::new(DefaultRouter::new(
Arc::clone(&network_graph),
Arc::clone(&logger),
Arc::clone(&keys_manager),
Arc::clone(&scorer),
probing_fee_params,
));
Arc::new(HighDegreeStrategy::new(
Arc::clone(&network_graph),
Arc::clone(&channel_manager),
probing_router,
*top_node_count,
DEFAULT_MIN_PROBE_AMOUNT_MSAT,
DEFAULT_MAX_PROBE_AMOUNT_MSAT,
probing_cfg.cooldown,
config.probing_liquidity_limit_multiplier,
))
},
ProbingStrategyKind::RandomWalk { max_hops } => Arc::new(RandomWalkStrategy::new(
Arc::clone(&network_graph),
Arc::clone(&channel_manager),
*max_hops,
DEFAULT_MIN_PROBE_AMOUNT_MSAT,
DEFAULT_MAX_PROBE_AMOUNT_MSAT,
)),
ProbingStrategyKind::Custom(s) => Arc::clone(s),
};
Arc::new(Prober {
channel_manager: Arc::clone(&channel_manager),
logger: Arc::clone(&logger),
strategy,
interval: probing_cfg.interval,
max_locked_msat: probing_cfg.max_locked_msat,
})
});

Ok(Node {
runtime,
stop_sender,
Expand DownExpand Up@@ -2252,6 +2340,7 @@ fn build_with_store_internal(
om_mailbox,
async_payments_role,
hrn_resolver,
prober,
#[cfg(cycle_tests)]
_leak_checker,
})
Expand Down
6 changes: 6 additions & 0 deletions src/config.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,6 +28,12 @@ const DEFAULT_BDK_WALLET_SYNC_INTERVAL_SECS: u64 = 80;
const DEFAULT_LDK_WALLET_SYNC_INTERVAL_SECS: u64 = 30;
const DEFAULT_FEE_RATE_CACHE_UPDATE_INTERVAL_SECS: u64 = 60 * 10;
const DEFAULT_PROBING_LIQUIDITY_LIMIT_MULTIPLIER: u64 = 3;
pub(crate) const DEFAULT_PROBING_INTERVAL_SECS: u64 = 10;
pub(crate) const MIN_PROBING_INTERVAL: Duration = Duration::from_millis(100);
pub(crate) const DEFAULT_PROBED_NODE_COOLDOWN_SECS: u64 = 60 * 60; // 1 hour
pub(crate) const DEFAULT_MAX_PROBE_LOCKED_MSAT: u64 = 100_000_000; // 100k sats
pub(crate) const DEFAULT_MIN_PROBE_AMOUNT_MSAT: u64 = 1_000_000; // 1k sats
pub(crate) const DEFAULT_MAX_PROBE_AMOUNT_MSAT: u64 = 10_000_000; // 10k sats
const DEFAULT_ANCHOR_PER_CHANNEL_RESERVE_SATS: u64 = 25_000;

// The default timeout after which we abort a wallet syncing operation.
Expand Down
31 changes: 21 additions & 10 deletions src/event.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -52,6 +52,7 @@ use crate::payment::store::{
PaymentDetails, PaymentDetailsUpdate, PaymentDirection, PaymentKind, PaymentStatus,
};
use crate::payment::PaymentMetadata;
use crate::probing::Prober;
use crate::runtime::Runtime;
use crate::types::{
CustomTlvRecord, DynStore, KeysManager, OnionMessenger, PaymentStore, Sweeper, Wallet,
Expand DownExpand Up@@ -536,12 +537,13 @@ where
payment_store: Arc<PaymentStore>,
peer_store: Arc<PeerStore<L>>,
keys_manager: Arc<KeysManager>,
runtime: Arc<Runtime>,
logger: L,
config: Arc<Config>,
static_invoice_store: Option<StaticInvoiceStore>,
onion_messenger: Arc<OnionMessenger>,
om_mailbox: Option<Arc<OnionMessageMailbox>>,
prober: Option<Arc<Prober>>,
runtime: Arc<Runtime>,
logger: L,
config: Arc<Config>,
}

impl<L: Deref + Clone + Sync + Send + 'static> EventHandler<L>
Expand All@@ -556,8 +558,8 @@ where
liquidity_source: Arc<LiquiditySource<Arc<Logger>>>, payment_store: Arc<PaymentStore>,
peer_store: Arc<PeerStore<L>>, keys_manager: Arc<KeysManager>,
static_invoice_store: Option<StaticInvoiceStore>, onion_messenger: Arc<OnionMessenger>,
om_mailbox: Option<Arc<OnionMessageMailbox>>, runtime: Arc<Runtime>, logger: L,
config: Arc<Config>,
om_mailbox: Option<Arc<OnionMessageMailbox>>, prober: Option<Arc<Prober>>,
runtime: Arc<Runtime>, logger: L, config: Arc<Config>,
) -> Self {
Self {
event_queue,
Expand All@@ -571,12 +573,13 @@ where
payment_store,
peer_store,
keys_manager,
logger,
runtime,
config,
static_invoice_store,
onion_messenger,
om_mailbox,
prober,
runtime,
logger,
config,
}
}

Expand DownExpand Up@@ -1208,8 +1211,16 @@ where

LdkEvent::PaymentPathSuccessful { .. } => {},
LdkEvent::PaymentPathFailed { .. } => {},
LdkEvent::ProbeSuccessful { .. } => {},
LdkEvent::ProbeFailed { .. } => {},
LdkEvent::ProbeSuccessful { path, payment_id, .. } => {
if let Some(prober) = &self.prober {
prober.handle_background_probe_successful(&path, payment_id);
}
},
LdkEvent::ProbeFailed { path, payment_id, .. } => {
if let Some(prober) = &self.prober {
prober.handle_background_probe_failed(&path, payment_id);
}
},
LdkEvent::HTLCHandlingFailed { failure_type, .. } => {
self.liquidity_source
.lsps2_service()
Expand Down
1 change: 1 addition & 0 deletions src/ffi/types.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -149,6 +149,7 @@ pub use crate::entropy::{generate_entropy_mnemonic, NodeEntropy, WordCount};
use crate::error::Error;
pub use crate::liquidity::LSPS1OrderStatus;
pub use crate::logger::{LogLevel, LogRecord, LogWriter};
pub use crate::probing::ProbingConfig;
use crate::{hex_utils, SocketAddress, UserChannelId};

uniffi::custom_type!(PublicKey, String, {
Expand Down
19 changes: 19 additions & 0 deletions src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -101,10 +101,12 @@ pub mod logger;
mod message_handler;
pub mod payment;
mod peer_store;
pub mod probing;
mod runtime;
mod scoring;
mod tx_broadcaster;
mod types;
mod util;
mod wallet;

use std::default::Default;
Expand DownExpand Up@@ -172,6 +174,9 @@ use payment::{
UnifiedPayment,
};
use peer_store::{PeerInfo, PeerStore};
#[cfg(feature = "uniffi")]
pub use probing::ArcedProbingConfigBuilder as ProbingConfigBuilder;
use probing::{run_prober, Prober};
use runtime::Runtime;
pub use tokio;
use types::{
Expand DownExpand Up@@ -250,6 +255,7 @@ pub struct Node {
om_mailbox: Option<Arc<OnionMessageMailbox>>,
async_payments_role: Option<AsyncPaymentsRole>,
hrn_resolver: HRNResolver,
prober: Option<Arc<Prober>>,
#[cfg(cycle_tests)]
_leak_checker: LeakChecker,
}
Expand DownExpand Up@@ -610,11 +616,19 @@ impl Node {
static_invoice_store,
Arc::clone(&self.onion_messenger),
self.om_mailbox.clone(),
self.prober.clone(),
Arc::clone(&self.runtime),
Arc::clone(&self.logger),
Arc::clone(&self.config),
));

if let Some(prober) = self.prober.clone() {
let stop_rx = self.stop_sender.subscribe();
self.runtime.spawn_cancellable_background_task(async move {
run_prober(prober, stop_rx).await;
});
}

// Setup background processing
let background_persister = Arc::clone(&self.kv_store);
let background_event_handler = Arc::clone(&event_handler);
Expand DownExpand Up@@ -1145,6 +1159,11 @@ impl Node {
))
}

/// Returns a reference to the [`Prober`], or `None` if no probing strategy is configured.
pub fn prober(&self) -> Option<&Prober> {
self.prober.as_deref()
}

/// Retrieve a list of known channels.
pub fn list_channels(&self) -> Vec<ChannelDetails> {
self.channel_manager
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions bindings/ldk_node.udl
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,6 +13,8 @@ typedef dictionary TorConfig;

typedef interface NodeEntropy;

typedef interface ProbingConfig;

typedef enum WordCount;

[Remote]
Expand All@@ -32,6 +34,18 @@ interface LogWriter {
void log(LogRecord record);
};

interface ProbingConfigBuilder {
[Name=high_degree]
constructor(u64 top_node_count);
[Name=random_walk]
constructor(u64 max_hops);
void set_interval(u64 secs);
void set_max_locked_msat(u64 max_msat);
void set_diversity_penalty_msat(u64 penalty_msat);
void set_cooldown(u64 secs);
ProbingConfig build();
};

interface Builder {
constructor();
[Name=from_config]
Expand DownExpand Up@@ -59,6 +73,7 @@ interface Builder {
void set_node_alias(string node_alias);
[Throws=BuildError]
void set_async_payments_role(AsyncPaymentsRole? role);
void set_probing_config(ProbingConfig config);
[Throws=BuildError]
Node build(NodeEntropy node_entropy);
[Throws=BuildError]
Expand Down
93 changes: 91 additions & 2 deletions src/builder.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -50,6 +50,7 @@ use crate::config::{
default_user_config, may_announce_channel, AnnounceError, AsyncPaymentsRole,
BitcoindRestClientConfig, Config, ElectrumSyncConfig, EsploraSyncConfig, HRNResolverConfig,
TorConfig, DEFAULT_ESPLORA_SERVER_URL, DEFAULT_LOG_FILENAME, DEFAULT_LOG_LEVEL,
DEFAULT_MAX_PROBE_AMOUNT_MSAT, DEFAULT_MIN_PROBE_AMOUNT_MSAT,
};
use crate::connection::ConnectionManager;
use crate::entropy::NodeEntropy;
Expand All@@ -74,6 +75,10 @@ use crate::logger::{log_error, LdkLogger, LogLevel, LogWriter, Logger};
use crate::message_handler::NodeCustomMessageHandler;
use crate::payment::asynchronous::om_mailbox::OnionMessageMailbox;
use crate::peer_store::PeerStore;
use crate::probing::{
HighDegreeStrategy, Prober, ProbingConfig, ProbingStrategy, ProbingStrategyKind,
RandomWalkStrategy,
};
use crate::runtime::{Runtime, RuntimeSpawner};
use crate::tx_broadcaster::TransactionBroadcaster;
use crate::types::{
Expand DownExpand Up@@ -306,6 +311,7 @@ pub struct NodeBuilder {
async_payments_role: Option<AsyncPaymentsRole>,
runtime_handle: Option<tokio::runtime::Handle>,
pathfinding_scores_sync_config: Option<PathfindingScoresSyncConfig>,
probing_config: Option<ProbingConfig>,
}

impl NodeBuilder {
Expand All@@ -323,6 +329,7 @@ impl NodeBuilder {
let log_writer_config = None;
let runtime_handle = None;
let pathfinding_scores_sync_config = None;
let probing_config = None;
Self {
config,
chain_data_source_config,
Expand All@@ -332,6 +339,7 @@ impl NodeBuilder {
runtime_handle,
async_payments_role: None,
pathfinding_scores_sync_config,
probing_config,
}
}

Expand DownExpand Up@@ -629,6 +637,31 @@ impl NodeBuilder {
Ok(self)
}

/// Sets background probing config.
///
/// Use [`ProbingConfigBuilder`] to build the configuration:
/// ```no_run
/// # #[cfg(not(feature = "uniffi"))]
/// # {
/// use std::time::Duration;
/// use ldk_node::Builder;
/// use ldk_node::probing::ProbingConfigBuilder;
///
/// let mut builder = Builder::new();
/// builder.set_probing_config(
/// ProbingConfigBuilder::high_degree(100)
/// .interval(Duration::from_secs(30))
/// .build()
/// );
/// # }
/// ```
///
/// [`ProbingConfigBuilder`]: crate::probing::ProbingConfigBuilder
pub fn set_probing_config(&mut self, config: ProbingConfig) -> &mut Self {
self.probing_config = Some(config);
self
}

/// Builds a [`Node`] instance with a [`SqliteStore`] backend and according to the options
/// previously configured.
pub fn build(&self, node_entropy: NodeEntropy) -> Result<Node, BuildError> {
Expand DownExpand Up@@ -868,6 +901,7 @@ impl NodeBuilder {
self.gossip_source_config.as_ref(),
self.liquidity_source_config.as_ref(),
self.pathfinding_scores_sync_config.as_ref(),
self.probing_config.as_ref(),
self.async_payments_role,
seed_bytes,
runtime,
Expand DownExpand Up@@ -1166,6 +1200,15 @@ impl ArcedNodeBuilder {
self.inner.write().expect("lock").set_async_payments_role(role).map(|_| ())
}

/// Configures background probing.
///
/// Use [`ProbingConfigBuilder`] to build the configuration.
///
/// [`ProbingConfigBuilder`]: crate::probing::ProbingConfigBuilder
pub fn set_probing_config(&self, config: Arc<ProbingConfig>) {
self.inner.write().expect("lock").set_probing_config((*config).clone());
}

/// Builds a [`Node`] instance with a [`SqliteStore`] backend and according to the options
/// previously configured.
pub fn build(&self, node_entropy: Arc<NodeEntropy>) -> Result<Arc<Node>, BuildError> {
Expand DownExpand Up@@ -1361,8 +1404,8 @@ fn build_with_store_internal(
gossip_source_config: Option<&GossipSourceConfig>,
liquidity_source_config: Option<&LiquiditySourceConfig>,
pathfinding_scores_sync_config: Option<&PathfindingScoresSyncConfig>,
async_payments_role: Option<AsyncPaymentsRole>, seed_bytes: [u8; 64], runtime: Arc<Runtime>,
logger: Arc<Logger>, kv_store: Arc<DynStore>,
probing_config: Option<&ProbingConfig>, async_payments_role: Option<AsyncPaymentsRole>,
seed_bytes: [u8; 64], runtime: Arc<Runtime>, logger: Arc<Logger>, kv_store: Arc<DynStore>,
) -> Result<Node, BuildError> {
optionally_install_rustls_cryptoprovider();

Expand DownExpand Up@@ -2219,6 +2262,51 @@ fn build_with_store_internal(
_leak_checker.0.push(Arc::downgrade(&wallet) as Weak<dyn Any + Send + Sync>);
}

let prober = probing_config.map(|probing_cfg| {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Would be better to move this up before the leak checker setup.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

moved

let strategy: Arc<dyn ProbingStrategy> = match &probing_cfg.kind {
ProbingStrategyKind::HighDegree { top_node_count } => {
// Dedicated router for probing so the diversity penalty doesn't interfere
// with real payments; shares the scorer so probe results still train it.
let mut probing_fee_params = ProbabilisticScoringFeeParameters::default();
Comment thread
randomlogin marked this conversation as resolved.
if let Some(penalty) = probing_cfg.diversity_penalty_msat {
probing_fee_params.probing_diversity_penalty_msat = penalty;
}
let probing_router = Arc::new(DefaultRouter::new(
Arc::clone(&network_graph),
Arc::clone(&logger),
Arc::clone(&keys_manager),
Arc::clone(&scorer),
probing_fee_params,
));
Arc::new(HighDegreeStrategy::new(
Arc::clone(&network_graph),
Arc::clone(&channel_manager),
probing_router,
*top_node_count,
DEFAULT_MIN_PROBE_AMOUNT_MSAT,
DEFAULT_MAX_PROBE_AMOUNT_MSAT,
probing_cfg.cooldown,
config.probing_liquidity_limit_multiplier,
))
},
ProbingStrategyKind::RandomWalk { max_hops } => Arc::new(RandomWalkStrategy::new(
Arc::clone(&network_graph),
Arc::clone(&channel_manager),
*max_hops,
DEFAULT_MIN_PROBE_AMOUNT_MSAT,
DEFAULT_MAX_PROBE_AMOUNT_MSAT,
)),
ProbingStrategyKind::Custom(s) => Arc::clone(s),
};
Arc::new(Prober {
channel_manager: Arc::clone(&channel_manager),
logger: Arc::clone(&logger),
strategy,
interval: probing_cfg.interval,
max_locked_msat: probing_cfg.max_locked_msat,
})
});

Ok(Node {
runtime,
stop_sender,
Expand DownExpand Up@@ -2252,6 +2340,7 @@ fn build_with_store_internal(
om_mailbox,
async_payments_role,
hrn_resolver,
prober,
#[cfg(cycle_tests)]
_leak_checker,
})
Expand Down
6 changes: 6 additions & 0 deletions src/config.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,6 +28,12 @@ const DEFAULT_BDK_WALLET_SYNC_INTERVAL_SECS: u64 = 80;
const DEFAULT_LDK_WALLET_SYNC_INTERVAL_SECS: u64 = 30;
const DEFAULT_FEE_RATE_CACHE_UPDATE_INTERVAL_SECS: u64 = 60 * 10;
const DEFAULT_PROBING_LIQUIDITY_LIMIT_MULTIPLIER: u64 = 3;
pub(crate) const DEFAULT_PROBING_INTERVAL_SECS: u64 = 10;
pub(crate) const MIN_PROBING_INTERVAL: Duration = Duration::from_millis(100);
pub(crate) const DEFAULT_PROBED_NODE_COOLDOWN_SECS: u64 = 60 * 60; // 1 hour
pub(crate) const DEFAULT_MAX_PROBE_LOCKED_MSAT: u64 = 100_000_000; // 100k sats
pub(crate) const DEFAULT_MIN_PROBE_AMOUNT_MSAT: u64 = 1_000_000; // 1k sats
pub(crate) const DEFAULT_MAX_PROBE_AMOUNT_MSAT: u64 = 10_000_000; // 10k sats
const DEFAULT_ANCHOR_PER_CHANNEL_RESERVE_SATS: u64 = 25_000;

// The default timeout after which we abort a wallet syncing operation.
Expand Down
31 changes: 21 additions & 10 deletions src/event.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -52,6 +52,7 @@ use crate::payment::store::{
PaymentDetails, PaymentDetailsUpdate, PaymentDirection, PaymentKind, PaymentStatus,
};
use crate::payment::PaymentMetadata;
use crate::probing::Prober;
use crate::runtime::Runtime;
use crate::types::{
CustomTlvRecord, DynStore, KeysManager, OnionMessenger, PaymentStore, Sweeper, Wallet,
Expand DownExpand Up@@ -536,12 +537,13 @@ where
payment_store: Arc<PaymentStore>,
peer_store: Arc<PeerStore<L>>,
keys_manager: Arc<KeysManager>,
runtime: Arc<Runtime>,
logger: L,
config: Arc<Config>,
static_invoice_store: Option<StaticInvoiceStore>,
onion_messenger: Arc<OnionMessenger>,
om_mailbox: Option<Arc<OnionMessageMailbox>>,
prober: Option<Arc<Prober>>,
runtime: Arc<Runtime>,
logger: L,
config: Arc<Config>,
}

impl<L: Deref + Clone + Sync + Send + 'static> EventHandler<L>
Expand All@@ -556,8 +558,8 @@ where
liquidity_source: Arc<LiquiditySource<Arc<Logger>>>, payment_store: Arc<PaymentStore>,
peer_store: Arc<PeerStore<L>>, keys_manager: Arc<KeysManager>,
static_invoice_store: Option<StaticInvoiceStore>, onion_messenger: Arc<OnionMessenger>,
om_mailbox: Option<Arc<OnionMessageMailbox>>, runtime: Arc<Runtime>, logger: L,
config: Arc<Config>,
om_mailbox: Option<Arc<OnionMessageMailbox>>, prober: Option<Arc<Prober>>,
runtime: Arc<Runtime>, logger: L, config: Arc<Config>,
) -> Self {
Self {
event_queue,
Expand All@@ -571,12 +573,13 @@ where
payment_store,
peer_store,
keys_manager,
logger,
runtime,
config,
static_invoice_store,
onion_messenger,
om_mailbox,
prober,
runtime,
logger,
config,
}
}

Expand DownExpand Up@@ -1208,8 +1211,16 @@ where

LdkEvent::PaymentPathSuccessful { .. } => {},
LdkEvent::PaymentPathFailed { .. } => {},
LdkEvent::ProbeSuccessful { .. } => {},
LdkEvent::ProbeFailed { .. } => {},
LdkEvent::ProbeSuccessful { path, payment_id, .. } => {
if let Some(prober) = &self.prober {
prober.handle_background_probe_successful(&path, payment_id);
}
},
LdkEvent::ProbeFailed { path, payment_id, .. } => {
if let Some(prober) = &self.prober {
prober.handle_background_probe_failed(&path, payment_id);
}
},
LdkEvent::HTLCHandlingFailed { failure_type, .. } => {
self.liquidity_source
.lsps2_service()
Expand Down
1 change: 1 addition & 0 deletions src/ffi/types.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -149,6 +149,7 @@ pub use crate::entropy::{generate_entropy_mnemonic, NodeEntropy, WordCount};
use crate::error::Error;
pub use crate::liquidity::LSPS1OrderStatus;
pub use crate::logger::{LogLevel, LogRecord, LogWriter};
pub use crate::probing::ProbingConfig;
use crate::{hex_utils, SocketAddress, UserChannelId};

uniffi::custom_type!(PublicKey, String, {
Expand Down
19 changes: 19 additions & 0 deletions src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -101,10 +101,12 @@ pub mod logger;
mod message_handler;
pub mod payment;
mod peer_store;
pub mod probing;
mod runtime;
mod scoring;
mod tx_broadcaster;
mod types;
mod util;
mod wallet;

use std::default::Default;
Expand DownExpand Up@@ -172,6 +174,9 @@ use payment::{
UnifiedPayment,
};
use peer_store::{PeerInfo, PeerStore};
#[cfg(feature = "uniffi")]
pub use probing::ArcedProbingConfigBuilder as ProbingConfigBuilder;
use probing::{run_prober, Prober};
use runtime::Runtime;
pub use tokio;
use types::{
Expand DownExpand Up@@ -250,6 +255,7 @@ pub struct Node {
om_mailbox: Option<Arc<OnionMessageMailbox>>,
async_payments_role: Option<AsyncPaymentsRole>,
hrn_resolver: HRNResolver,
prober: Option<Arc<Prober>>,
#[cfg(cycle_tests)]
_leak_checker: LeakChecker,
}
Expand DownExpand Up@@ -610,11 +616,19 @@ impl Node {
static_invoice_store,
Arc::clone(&self.onion_messenger),
self.om_mailbox.clone(),
self.prober.clone(),
Arc::clone(&self.runtime),
Arc::clone(&self.logger),
Arc::clone(&self.config),
));

if let Some(prober) = self.prober.clone() {
let stop_rx = self.stop_sender.subscribe();
self.runtime.spawn_cancellable_background_task(async move {
run_prober(prober, stop_rx).await;
});
}

// Setup background processing
let background_persister = Arc::clone(&self.kv_store);
let background_event_handler = Arc::clone(&event_handler);
Expand DownExpand Up@@ -1145,6 +1159,11 @@ impl Node {
))
}

/// Returns a reference to the [`Prober`], or `None` if no probing strategy is configured.
pub fn prober(&self) -> Option<&Prober> {
self.prober.as_deref()
}

/// Retrieve a list of known channels.
pub fn list_channels(&self) -> Vec<ChannelDetails> {
self.channel_manager
Expand Down
Loading
Loading