Skip to content

Commit 0bebc63

Browse files
author
sangbida
committed
Add docs to lib.rs
Add ValueOrRange logs Add NodeInfo logs Add PaymentResult docs Add PaymentOutcome docs Fix up url and add simulation logs Remove spurious change Add basic usage Update doc for WriteResults Add Simulation and Lightning error docs Add DestinationGenerator and PaymentGenerator docs quick tidy up of a few doc comments Fix up formatting and some language Fix up NodeInfo and NodeFeatures comments PR Fixes Fix line wrapping to 120 chars
1 parent 271db36 commit 0bebc63

File tree

2 files changed

+92
-12
lines changed

2 files changed

+92
-12
lines changed

simln-lib/README.md

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,20 @@
11
# sim-ln
22

3-
A Lightning Network simulation library that enables testing and analysis of payment routing behavior in a controlled environment.
3+
A Lightning Network simulation library that enables testing and analysis of payment routing behavior on any Lightning Network. While primarily designed for controlled environments, it can also be used with real networks like Bitcoin signet where you don't control all nodes.
44

55
## Overview
66

77
sim-ln provides a framework for simulating Lightning Network payment routing behavior, allowing developers and researchers to:
88

9-
- Create simulated Lightning Network topologies
10-
- Test payment routing strategies
11-
- Analyze network behavior under different conditions
12-
- Simulate real Lightning node implementations (LND, c-lightning, Eclair)
9+
- Generate specific or random traffic patterns on a provided Lightning graph.
10+
- Test payment routing strategies.
11+
- Analyze network behavior under different conditions.
1312

13+
## Usage
14+
15+
Add sim-ln to your Cargo.toml:
16+
17+
```toml
18+
[dependencies]
19+
sim-ln = "0.1.0"
20+
```

simln-lib/src/lib.rs

Lines changed: 80 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
#![deny(rustdoc::broken_intra_doc_links)]
2+
13
use async_trait::async_trait;
24
use bitcoin::secp256k1::PublicKey;
35
use bitcoin::Network;
@@ -36,13 +38,18 @@ pub mod sim_node;
3638
#[cfg(test)]
3739
mod test_utils;
3840

41+
/// Represents a node id, either by its public key or alias.
3942
#[derive(Serialize, Debug, Clone)]
4043
pub enum NodeId {
44+
/// The node's public key.
4145
PublicKey(PublicKey),
46+
/// The node's alias (human-readable name).
4247
Alias(String),
4348
}
4449

4550
impl NodeId {
51+
/// Validates that the provided node id matches the one returned by the backend. If the node id is an alias,
52+
/// it will be updated to the one returned by the backend if there is a mismatch.
4653
pub fn validate(&self, node_id: &PublicKey, alias: &mut String) -> Result<(), LightningError> {
4754
match self {
4855
crate::NodeId::PublicKey(pk) => {
@@ -67,6 +74,7 @@ impl NodeId {
6774
Ok(())
6875
}
6976

77+
/// Returns the public key of the node if it is a public key node id.
7078
pub fn get_pk(&self) -> Result<&PublicKey, String> {
7179
if let NodeId::PublicKey(pk) = self {
7280
Ok(pk)
@@ -93,21 +101,21 @@ impl std::fmt::Display for NodeId {
93101
#[derive(Debug, Clone, PartialEq, Eq, Hash, Copy)]
94102
pub struct ShortChannelID(u64);
95103

96-
/// Utility function to easily convert from u64 to `ShortChannelID`
104+
/// Utility function to easily convert from u64 to `ShortChannelID`.
97105
impl From<u64> for ShortChannelID {
98106
fn from(value: u64) -> Self {
99107
ShortChannelID(value)
100108
}
101109
}
102110

103-
/// Utility function to easily convert `ShortChannelID` into u64
111+
/// Utility function to easily convert `ShortChannelID` into u64.
104112
impl From<ShortChannelID> for u64 {
105113
fn from(scid: ShortChannelID) -> Self {
106114
scid.0
107115
}
108116
}
109117

110-
/// See https://github.com/lightning/bolts/blob/60de4a09727c20dea330f9ee8313034de6e50594/07-routing-gossip.md#definition-of-short_channel_id.
118+
/// See <https://github.com/lightning/bolts/blob/60de4a09727c20dea330f9ee8313034de6e50594/07-routing-gossip.md#definition-of-short_channel_id>
111119
impl std::fmt::Display for ShortChannelID {
112120
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
113121
write!(
@@ -124,7 +132,9 @@ impl std::fmt::Display for ShortChannelID {
124132
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
125133
#[serde(untagged)]
126134
pub enum ValueOrRange<T> {
135+
/// A single fixed value.
127136
Value(T),
137+
/// A range [min, max) from which values are randomly sampled.
128138
Range(T, T),
129139
}
130140

@@ -179,58 +189,87 @@ pub struct ActivityDefinition {
179189
pub amount_msat: Amount,
180190
}
181191

192+
/// Represents errors that can occur during simulation execution.
182193
#[derive(Debug, Error)]
183194
pub enum SimulationError {
195+
/// Error that occurred during Lightning Network operations.
184196
#[error("Lightning Error: {0:?}")]
185197
LightningError(#[from] LightningError),
198+
/// Error that occurred during task execution.
186199
#[error("TaskError")]
187200
TaskError,
201+
/// Error that occurred while writing CSV data.
188202
#[error("CSV Error: {0:?}")]
189203
CsvError(#[from] csv::Error),
204+
/// Error that occurred during file operations.
190205
#[error("File Error")]
191206
FileError,
207+
/// Error that occurred during random activity generation.
192208
#[error("{0}")]
193209
RandomActivityError(RandomActivityError),
210+
/// Error that occurred in the simulated network.
194211
#[error("Simulated Network Error: {0}")]
195212
SimulatedNetworkError(String),
213+
/// Error that occurred while accessing system time.
196214
#[error("System Time Error: {0}")]
197215
SystemTimeError(#[from] SystemTimeError),
216+
/// Error that occurred when a required node was not found.
198217
#[error("Missing Node Error: {0}")]
199218
MissingNodeError(String),
219+
/// Error that occurred in message passing channels.
200220
#[error("Mpsc Channel Error: {0}")]
201221
MpscChannelError(String),
222+
/// Error that occurred while generating payment parameters.
202223
#[error("Payment Generation Error: {0}")]
203224
PaymentGenerationError(PaymentGenerationError),
225+
/// Error that occurred while generating destination nodes.
204226
#[error("Destination Generation Error: {0}")]
205227
DestinationGenerationError(DestinationGenerationError),
206228
}
207229

230+
/// Represents errors that can occur during Lightning Network operations.
208231
#[derive(Debug, Error)]
209232
pub enum LightningError {
233+
/// Error that occurred while connecting to a Lightning node.
210234
#[error("Node connection error: {0}")]
211235
ConnectionError(String),
236+
/// Error that occurred while retrieving node information.
212237
#[error("Get info error: {0}")]
213238
GetInfoError(String),
239+
/// Error that occurred while sending a payment.
214240
#[error("Send payment error: {0}")]
215241
SendPaymentError(String),
242+
/// Error that occurred while tracking a payment.
216243
#[error("Track payment error: {0}")]
217244
TrackPaymentError(String),
245+
/// Error that occurred when a payment hash is invalid.
218246
#[error("Invalid payment hash")]
219247
InvalidPaymentHash,
248+
/// Error that occurred while retrieving information about a specific node.
220249
#[error("Get node info error: {0}")]
221250
GetNodeInfoError(String),
251+
/// Error that occurred during configuration validation.
222252
#[error("Config validation failed: {0}")]
223253
ValidationError(String),
254+
/// Error that represents a permanent failure condition.
224255
#[error("Permanent error: {0:?}")]
225256
PermanentError(String),
257+
/// Error that occurred while listing channels.
226258
#[error("List channels error: {0}")]
227259
ListChannelsError(String),
228260
}
229261

262+
/// Information about a Lightning Network node.
263+
/// - Alias: A human-readable name for the node.
264+
/// - Features: The node's supported protocol features and capabilities,
265+
/// used to determine compatibility and available
230266
#[derive(Debug, Clone)]
231267
pub struct NodeInfo {
268+
/// The node's public key.
232269
pub pubkey: PublicKey,
270+
/// A human-readable name for the node (may be empty).
233271
pub alias: String,
272+
/// The node's supported protocol features and capabilities.
234273
pub features: NodeFeatures,
235274
}
236275

@@ -251,7 +290,7 @@ impl Display for NodeInfo {
251290
pub trait LightningNode: Send {
252291
/// Get information about the node.
253292
fn get_info(&self) -> &NodeInfo;
254-
/// Get the network this node is running at
293+
/// Get the network this node is running at.
255294
async fn get_network(&mut self) -> Result<Network, LightningError>;
256295
/// Keysend payment worth `amount_msat` from a source node to the destination node.
257296
async fn send_payment(
@@ -265,17 +304,19 @@ pub trait LightningNode: Send {
265304
hash: &PaymentHash,
266305
shutdown: Listener,
267306
) -> Result<PaymentResult, LightningError>;
268-
/// Gets information on a specific node
307+
/// Gets information on a specific node.
269308
async fn get_node_info(&mut self, node_id: &PublicKey) -> Result<NodeInfo, LightningError>;
270309
/// Lists all channels, at present only returns a vector of channel capacities in msat because no further
271310
/// information is required.
272311
async fn list_channels(&mut self) -> Result<Vec<u64>, LightningError>;
273312
}
274313

314+
/// Represents an error that occurs when generating a destination for a payment.
275315
#[derive(Debug, Error)]
276316
#[error("Destination generation error: {0}")]
277317
pub struct DestinationGenerationError(String);
278318

319+
/// A trait for selecting destination nodes for payments in the Lightning Network.
279320
pub trait DestinationGenerator: Send {
280321
/// choose_destination picks a destination node within the network, returning the node's information and its
281322
/// capacity (if available).
@@ -285,15 +326,18 @@ pub trait DestinationGenerator: Send {
285326
) -> Result<(NodeInfo, Option<u64>), DestinationGenerationError>;
286327
}
287328

329+
/// Represents an error that occurs when generating payments.
288330
#[derive(Debug, Error)]
289331
#[error("Payment generation error: {0}")]
290332
pub struct PaymentGenerationError(String);
291333

334+
/// A trait for generating payment parameters in the Lightning Network.
292335
pub trait PaymentGenerator: Display + Send {
293-
/// Returns the time that the payments should start
336+
/// Returns the time that the payments should start.
294337
fn payment_start(&self) -> Option<Duration>;
295338

296-
/// Returns the number of payments that should be made
339+
/// Returns the number of payments that should be made.
340+
/// Returns `Some(n)` if there's a limit on the number of payments to dispatch, or `None` otherwise.
297341
fn payment_count(&self) -> Option<u64>;
298342

299343
/// Returns the number of seconds that a node should wait until firing its next payment.
@@ -306,20 +350,32 @@ pub trait PaymentGenerator: Display + Send {
306350
) -> Result<u64, PaymentGenerationError>;
307351
}
308352

353+
/// Represents the result of a payment attempt.
309354
#[derive(Debug, Clone, Serialize, Deserialize)]
310355
pub struct PaymentResult {
356+
/// The number of HTLCs (Hash Time Locked Contracts) used in the payment attempt.
357+
/// Multiple HTLCs may be used for a single payment when using techniques like multi-part payments or when
358+
/// retrying failed payment paths.
311359
pub htlc_count: usize,
360+
/// The final outcome of the payment attempt, indicating whether it succeeded or failed
361+
/// (and if failed, the reason for failure).
312362
pub payment_outcome: PaymentOutcome,
313363
}
314364

315365
impl PaymentResult {
366+
/// Creates a new PaymentResult indicating that the payment was never dispatched. This is used when there was an
367+
/// error during the initial payment dispatch attempt (e.g., insufficient balance, invalid destination) with
368+
/// [`PaymentOutcome::NotDispatched`].
316369
pub fn not_dispatched() -> Self {
317370
PaymentResult {
318371
htlc_count: 0,
319372
payment_outcome: PaymentOutcome::NotDispatched,
320373
}
321374
}
322375

376+
/// Creates a new PaymentResult indicating that tracking the payment failed. This is used when the payment was
377+
/// dispatched but the system was unable to determine its final outcome (e.g. due to connection issues or timeouts)
378+
/// with [`PaymentOutcome::TrackPaymentFailed`].
323379
pub fn track_payment_failed() -> Self {
324380
PaymentResult {
325381
htlc_count: 0,
@@ -338,19 +394,32 @@ impl Display for PaymentResult {
338394
}
339395
}
340396

397+
/// Represents all possible outcomes of a Lightning Network payment attempt.
341398
#[derive(Debug, Clone, Serialize, Deserialize)]
342399
pub enum PaymentOutcome {
400+
/// Payment completed successfully, reaching its intended recipient.
343401
Success,
402+
/// The recipient rejected the payment.
344403
RecipientRejected,
404+
/// The payment was cancelled by the sending user before completion.
345405
UserAbandoned,
406+
/// The payment failed after exhausting all retry attempts.
346407
RetriesExhausted,
408+
/// The payment expired before it could complete (e.g., HTLC timeout).
347409
PaymentExpired,
410+
/// No viable route could be found to the destination node.
348411
RouteNotFound,
412+
/// An unexpected error occurred during payment processing.
349413
UnexpectedError,
414+
/// The payment failed due to incorrect payment details (e.g., wrong invoice amount).
350415
IncorrectPaymentDetails,
416+
/// The sending node has insufficient balance to complete/dispatch the payment.
351417
InsufficientBalance,
418+
/// The payment failed for an unknown reason.
352419
Unknown,
420+
/// The payment was never dispatched due to an error during initial sending.
353421
NotDispatched,
422+
/// The payment was dispatched but its final status could not be determined.
354423
TrackPaymentFailed,
355424
}
356425

@@ -472,6 +541,9 @@ impl SimulationCfg {
472541
}
473542
}
474543

544+
/// A Lightning Network payment simulator that manages payment flows between nodes.
545+
/// The simulator can execute both predefined payment patterns and generate random payment activity
546+
/// based on configuration parameters.
475547
#[derive(Clone)]
476548
pub struct Simulation {
477549
/// Config for the simulation itself.
@@ -490,6 +562,7 @@ pub struct Simulation {
490562
shutdown_listener: Listener,
491563
}
492564

565+
/// Configuration for writing simulation results to CSV files.
493566
#[derive(Clone)]
494567
pub struct WriteResults {
495568
/// Data directory where CSV result files are written.

0 commit comments

Comments
 (0)