-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathmain.rs
285 lines (252 loc) · 9.95 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
use anyhow::anyhow;
use bitcoin::secp256k1::PublicKey;
use clap::builder::TypedValueParser;
use clap::Parser;
use log::LevelFilter;
use simln_lib::{
cln::ClnNode, lnd::LndNode, ActivityDefinition, LightningError, LightningNode, NodeConnection,
NodeId, SimParams, Simulation, SimulationCfg, WriteResults,
};
use simple_logger::SimpleLogger;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::Mutex;
/// The default directory where the simulation files are stored and where the results will be written to.
pub const DEFAULT_DATA_DIR: &str = ".";
/// The default simulation file to be used by the simulator.
pub const DEFAULT_SIM_FILE: &str = "sim.json";
/// The default expected payment amount for the simulation, around ~$10 at the time of writing.
pub const DEFAULT_EXPECTED_PAYMENT_AMOUNT: u64 = 3_800_000;
/// The number of times over each node in the network sends its total deployed capacity in a calendar month.
pub const DEFAULT_ACTIVITY_MULTIPLIER: f64 = 2.0;
/// Default batch size to flush result data to disk
const DEFAULT_PRINT_BATCH_SIZE: u32 = 500;
/// Deserializes a f64 as long as it is positive and greater than 0.
fn deserialize_f64_greater_than_zero(x: String) -> Result<f64, String> {
match x.parse::<f64>() {
Ok(x) => {
if x > 0.0 {
Ok(x)
} else {
Err(format!(
"capacity_multiplier must be higher than 0. {x} received."
))
}
},
Err(e) => Err(e.to_string()),
}
}
#[derive(Parser)]
#[command(version, about)]
struct Cli {
/// Path to a directory containing simulation files, and where simulation results will be stored
#[clap(long, short, default_value = DEFAULT_DATA_DIR)]
data_dir: PathBuf,
/// Path to the simulation file to be used by the simulator
/// This can either be an absolute path, or relative path with respect to data_dir
#[clap(long, short, default_value = DEFAULT_SIM_FILE)]
sim_file: PathBuf,
/// Total time the simulator will be running
#[clap(long, short)]
total_time: Option<u32>,
/// Number of activity results to batch together before printing to csv file [min: 1]
#[clap(long, short, default_value_t = DEFAULT_PRINT_BATCH_SIZE, value_parser = clap::builder::RangedU64ValueParser::<u32>::new().range(1..u32::MAX as u64))]
print_batch_size: u32,
/// Level of verbosity of the messages displayed by the simulator.
/// Possible values: [off, error, warn, info, debug, trace]
#[clap(long, short, verbatim_doc_comment, default_value = "info")]
log_level: LevelFilter,
/// Expected payment amount for the random activity generator
#[clap(long, short, default_value_t = DEFAULT_EXPECTED_PAYMENT_AMOUNT, value_parser = clap::builder::RangedU64ValueParser::<u64>::new().range(1..u64::MAX))]
expected_pmt_amt: u64,
/// Multiplier of the overall network capacity used by the random activity generator
#[clap(long, short, default_value_t = DEFAULT_ACTIVITY_MULTIPLIER, value_parser = clap::builder::StringValueParser::new().try_map(deserialize_f64_greater_than_zero))]
capacity_multiplier: f64,
/// Do not create an output file containing the simulations results
#[clap(long, default_value_t = false)]
no_results: bool,
/// Seed to run random activity generator deterministically
#[clap(long, short)]
fix_seed: Option<u64>,
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Enable tracing if building in developer mode.
#[cfg(feature = "dev")]
{
console_subscriber::init();
}
let cli = Cli::parse();
SimpleLogger::new()
.with_level(LevelFilter::Warn)
.with_module_level("simln_lib", cli.log_level)
.with_module_level("sim_cli", cli.log_level)
.init()
.unwrap();
let sim_path = read_sim_path(cli.data_dir.clone(), cli.sim_file).await?;
let SimParams { nodes, activity } =
serde_json::from_str(&std::fs::read_to_string(sim_path)?)
.map_err(|e| anyhow!("Could not deserialize node connection data or activity description from simulation file (line {}, col {}).", e.line(), e.column()))?;
let mut clients: HashMap<PublicKey, Arc<Mutex<dyn LightningNode>>> = HashMap::new();
let mut pk_node_map = HashMap::new();
let mut alias_node_map = HashMap::new();
for connection in nodes {
// TODO: Feels like there should be a better way of doing this without having to Arc<Mutex<T>>> it at this time.
// Box sort of works, but we won't know the size of the dyn LightningNode at compile time so the compiler will
// scream at us when trying to create the Arc<Mutex>> later on while adding the node to the clients map
let node: Arc<Mutex<dyn LightningNode>> = match connection {
NodeConnection::LND(c) => Arc::new(Mutex::new(LndNode::new(c).await?)),
NodeConnection::CLN(c) => Arc::new(Mutex::new(ClnNode::new(c).await?)),
};
let node_info = node.lock().await.get_info().clone();
log::info!(
"Connected to {} - Node ID: {}.",
node_info.alias,
node_info.pubkey
);
if clients.contains_key(&node_info.pubkey) {
anyhow::bail!(LightningError::ValidationError(format!(
"duplicated node: {}.",
node_info.pubkey
)));
}
if alias_node_map.contains_key(&node_info.alias) {
anyhow::bail!(LightningError::ValidationError(format!(
"duplicated node: {}.",
node_info.alias
)));
}
clients.insert(node_info.pubkey, node);
pk_node_map.insert(node_info.pubkey, node_info.clone());
alias_node_map.insert(node_info.alias.clone(), node_info);
}
let mut validated_activities = vec![];
// Make all the activities identifiable by PK internally
for act in activity.into_iter() {
// We can only map aliases to nodes we control, so if either the source or destination alias
// is not in alias_node_map, we fail
let source = if let Some(source) = match &act.source {
NodeId::PublicKey(pk) => pk_node_map.get(pk),
NodeId::Alias(a) => alias_node_map.get(a),
} {
source.clone()
} else {
anyhow::bail!(LightningError::ValidationError(format!(
"activity source {} not found in nodes.",
act.source
)));
};
let destination = match &act.destination {
NodeId::Alias(a) => {
if let Some(info) = alias_node_map.get(a) {
info.clone()
} else {
anyhow::bail!(LightningError::ValidationError(format!(
"unknown activity destination: {}.",
act.destination
)));
}
},
NodeId::PublicKey(pk) => {
if let Some(info) = pk_node_map.get(pk) {
info.clone()
} else {
clients
.get(&source.pubkey)
.unwrap()
.lock()
.await
.get_node_info(pk)
.await
.map_err(|e| {
log::debug!("{}", e);
LightningError::ValidationError(format!(
"Destination node unknown or invalid: {}.",
pk,
))
})?
}
},
};
validated_activities.push(ActivityDefinition {
source,
destination,
start_secs: act.start_secs,
count: act.count,
interval_secs: act.interval_secs,
amount_msat: act.amount_msat,
});
}
let write_results = if !cli.no_results {
Some(WriteResults {
results_dir: mkdir(cli.data_dir.join("results")).await?,
batch_size: cli.print_batch_size,
})
} else {
None
};
let sim = Simulation::new(
SimulationCfg::new(
cli.total_time,
cli.expected_pmt_amt,
cli.capacity_multiplier,
write_results,
cli.fix_seed,
),
clients,
validated_activities,
);
let sim2 = sim.clone();
ctrlc::set_handler(move || {
log::info!("Shutting down simulation.");
sim2.shutdown();
})?;
sim.run().await?;
Ok(())
}
async fn read_sim_path(data_dir: PathBuf, sim_file: PathBuf) -> anyhow::Result<PathBuf> {
let sim_path = if sim_file.is_relative() {
data_dir.join(sim_file)
} else {
sim_file
};
if sim_path.exists() {
Ok(sim_path)
} else {
log::info!("Simulation file '{}' does not exist.", sim_path.display());
select_sim_file(data_dir).await
}
}
async fn select_sim_file(data_dir: PathBuf) -> anyhow::Result<PathBuf> {
let sim_files = std::fs::read_dir(data_dir.clone())?
.filter_map(|f| {
f.ok().and_then(|f| {
if f.path().extension()?.to_str()? == "json" {
f.file_name().into_string().ok()
} else {
None
}
})
})
.collect::<Vec<_>>();
if sim_files.is_empty() {
anyhow::bail!(
"no simulation files found in {}.",
data_dir.canonicalize()?.display()
);
}
let selection = dialoguer::Select::new()
.with_prompt(format!(
"Select a simulation file. Found these in {}",
data_dir.canonicalize()?.display()
))
.items(&sim_files)
.default(0)
.interact()?;
Ok(data_dir.join(sim_files[selection].clone()))
}
async fn mkdir(dir: PathBuf) -> anyhow::Result<PathBuf> {
tokio::fs::create_dir_all(&dir).await?;
Ok(dir)
}