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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
#![allow(trivial_numeric_casts)]
use crate::{Error, Result};
use log::{debug, Level};
use serde::{Deserialize, Serialize};
use sn_routing::TransportConfig as NetworkConfig;
use std::{
collections::HashSet,
fs::{self, File},
io::{self, BufReader},
net::{IpAddr, Ipv4Addr, SocketAddr},
path::PathBuf,
};
use structopt::StructOpt;
const CONFIG_FILE: &str = "node.config";
const CONNECTION_INFO_FILE: &str = "node_connection_info.config";
const DEFAULT_ROOT_DIR_NAME: &str = "root_dir";
const DEFAULT_MAX_CAPACITY: u64 = 2 * 1024 * 1024 * 1024;
#[derive(Default, Clone, Debug, Serialize, Deserialize, Eq, PartialEq, StructOpt)]
#[structopt(rename_all = "kebab-case", bin_name = "sn_node")]
#[structopt(global_settings = &[structopt::clap::AppSettings::ColoredHelp])]
pub struct Config {
#[structopt(short, long, parse(try_from_str))]
pub wallet_id: Option<String>,
#[structopt(short, long)]
pub max_capacity: Option<u64>,
#[structopt(short, long, parse(from_os_str))]
pub root_dir: Option<PathBuf>,
#[structopt(short, long, parse(from_occurrences))]
pub verbose: u64,
#[structopt(long)]
pub completions: Option<String>,
#[structopt(long)]
pub log_dir: Option<PathBuf>,
#[structopt(long)]
pub update: bool,
#[structopt(long)]
pub update_only: bool,
#[structopt(long)]
pub clear_data: bool,
#[structopt(long)]
pub first: Option<SocketAddr>,
#[structopt(long)]
pub local_addr: Option<SocketAddr>,
#[structopt(long)]
pub public_addr: Option<SocketAddr>,
#[structopt(long)]
pub skip_igd: bool,
#[structopt(
short,
long,
default_value = "[]",
parse(try_from_str = serde_json::from_str)
)]
pub hard_coded_contacts: HashSet<SocketAddr>,
#[structopt(long)]
pub max_msg_size_allowed: Option<u32>,
#[structopt(long)]
pub idle_timeout_msec: Option<u64>,
#[structopt(long)]
pub keep_alive_interval_msec: Option<u32>,
#[structopt(long)]
pub bootstrap_cache_dir: Option<String>,
#[structopt(long)]
pub upnp_lease_duration: Option<u32>,
#[structopt(skip)]
#[allow(missing_docs)]
pub network_config: NetworkConfig,
}
impl Config {
pub fn new() -> Result<Self, Error> {
let mut config = match Self::read_from_file() {
Ok(Some(config)) => config,
Ok(None) | Err(_) => Default::default(),
};
let mut command_line_args = Config::from_args();
command_line_args.validate()?;
if let Some(socket_addr) = command_line_args.first {
command_line_args.local_addr = Some(socket_addr);
}
config.merge(command_line_args);
config.clear_data_from_disk().unwrap_or_else(|_| {
log::error!("Error deleting data file from disk");
});
Ok(config)
}
fn validate(&mut self) -> Result<(), Error> {
if let Some(_external_addr) = self.public_addr {
if self.first.is_none() && self.local_addr.is_none() {
return Err(Error::Configuration("--public-addr passed without specifing local address using --first or --local-addr".to_string()));
}
}
if self.public_addr.is_none() && self.local_addr.is_some() {
if self.skip_igd {
self.public_addr = self.local_addr;
} else {
println!("Warning: Local Address provided is skipped since external address is not provided.");
self.local_addr = None;
}
}
Ok(())
}
fn merge(&mut self, config: Config) {
if let Some(wallet_id) = config.wallet_id() {
self.wallet_id = Some(wallet_id.clone());
}
if let Some(max_capacity) = &config.max_capacity {
self.max_capacity = Some(*max_capacity);
}
if let Some(root_dir) = &config.root_dir {
self.root_dir = Some(root_dir.clone());
}
if config.verbose > 0 {
self.verbose = config.verbose;
}
if let Some(completions) = &config.completions {
self.completions = Some(completions.clone());
}
if let Some(log_dir) = &config.log_dir {
self.log_dir = Some(log_dir.clone());
}
self.update = config.update || self.update;
self.update_only = config.update_only || self.update_only;
self.clear_data = config.clear_data || self.clear_data;
if let Some(socket_addr) = config.first {
self.first = Some(socket_addr);
self.local_addr = Some(socket_addr);
}
if let Some(local_addr) = config.local_addr {
self.local_addr = config.local_addr;
self.network_config.local_port = Some(local_addr.port());
self.network_config.local_ip = Some(local_addr.ip());
}
if let Some(public_addr) = config.public_addr {
self.public_addr = config.public_addr;
self.network_config.external_port = Some(public_addr.port());
self.network_config.external_ip = Some(public_addr.ip());
}
self.network_config.forward_port = !config.skip_igd;
if !config.hard_coded_contacts.is_empty() {
self.network_config.hard_coded_contacts = config.hard_coded_contacts;
}
if let Some(max_msg_size) = config.max_msg_size_allowed {
self.network_config.max_msg_size_allowed = Some(max_msg_size);
}
if let Some(idle_timeout) = config.idle_timeout_msec {
self.network_config.idle_timeout_msec = Some(idle_timeout);
}
if let Some(keep_alive) = config.keep_alive_interval_msec {
self.network_config.keep_alive_interval_msec = Some(keep_alive);
}
if let Some(bootstrap_cache_dir) = config.bootstrap_cache_dir {
self.network_config.bootstrap_cache_dir = Some(bootstrap_cache_dir);
}
if let Some(upnp_lease_duration) = config.upnp_lease_duration {
self.network_config.upnp_lease_duration = Some(upnp_lease_duration);
}
}
pub fn wallet_id(&self) -> Option<&String> {
self.wallet_id.as_ref()
}
pub fn is_first(&self) -> bool {
self.first.is_some()
}
pub fn max_capacity(&self) -> u64 {
self.max_capacity.unwrap_or(DEFAULT_MAX_CAPACITY)
}
pub fn root_dir(&self) -> Result<PathBuf> {
Ok(match &self.root_dir {
Some(root_dir) => root_dir.clone(),
None => project_dirs()?.join(DEFAULT_ROOT_DIR_NAME),
})
}
pub fn set_root_dir<P: Into<PathBuf>>(&mut self, path: P) {
self.root_dir = Some(path.into())
}
pub fn set_log_dir<P: Into<PathBuf>>(&mut self, path: P) {
self.log_dir = Some(path.into())
}
pub fn verbose(&self) -> Level {
match self.verbose {
0 => Level::Error,
1 => Level::Warn,
2 => Level::Info,
3 => Level::Debug,
_ => Level::Trace,
}
}
pub fn network_config(&self) -> &NetworkConfig {
&self.network_config
}
pub fn set_network_config(&mut self, config: NetworkConfig) {
self.network_config = config;
}
pub fn completions(&self) -> &Option<String> {
&self.completions
}
pub fn log_dir(&self) -> &Option<PathBuf> {
&self.log_dir
}
pub fn update(&self) -> bool {
self.update
}
pub fn update_only(&self) -> bool {
self.update_only
}
pub fn listen_on_loopback(&mut self) {
self.network_config.local_ip = Some(IpAddr::V4(Ipv4Addr::LOCALHOST));
}
fn clear_data_from_disk(&self) -> Result<()> {
if self.clear_data {
let path = project_dirs()?.join(self.root_dir()?);
if path.exists() {
std::fs::remove_dir_all(&path)?;
}
}
Ok(())
}
fn read_from_file() -> Result<Option<Config>> {
let path = project_dirs()?.join(CONFIG_FILE);
match File::open(&path) {
Ok(file) => {
debug!("Reading settings from {}", path.display());
let reader = BufReader::new(file);
let config = serde_json::from_reader(reader)?;
Ok(config)
}
Err(error) => {
if error.kind() == std::io::ErrorKind::NotFound {
debug!("No config file available at {}", path.display());
Ok(None)
} else {
Err(error.into())
}
}
}
}
pub fn write_to_disk(&self) -> Result<()> {
write_file(CONFIG_FILE, self)
}
}
pub fn set_connection_info(contact: SocketAddr) -> Result<()> {
write_file(CONNECTION_INFO_FILE, &vec![contact])
}
pub fn add_connection_info(contact: SocketAddr) -> Result<()> {
let hard_coded_contacts = if let Ok(mut hard_coded_contacts) = read_conn_info_from_file() {
let _ = hard_coded_contacts.insert(contact);
hard_coded_contacts
} else {
vec![contact].into_iter().collect()
};
write_file(CONNECTION_INFO_FILE, &hard_coded_contacts)
}
fn read_conn_info_from_file() -> Result<HashSet<SocketAddr>> {
let path = project_dirs()?.join(CONNECTION_INFO_FILE);
match File::open(&path) {
Ok(file) => {
debug!("Reading connection info from {}", path.display());
let reader = BufReader::new(file);
let config = serde_json::from_reader(reader)?;
Ok(config)
}
Err(error) => {
if error.kind() == std::io::ErrorKind::NotFound {
debug!("No connection info file available at {}", path.display());
}
Err(error.into())
}
}
}
fn write_file<T: ?Sized>(file: &str, config: &T) -> Result<()>
where
T: Serialize,
{
let project_dirs = project_dirs()?;
fs::create_dir_all(project_dirs.clone())?;
let path = project_dirs.join(file);
let mut file = File::create(&path)?;
serde_json::to_writer_pretty(&mut file, config)?;
file.sync_all()?;
Ok(())
}
fn project_dirs() -> Result<PathBuf> {
let mut home_dir = dirs_next::home_dir()
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "Home directory not found"))?;
home_dir.push(".safe");
home_dir.push("node");
Ok(home_dir)
}
#[test]
fn smoke() {
let expected_size = 504;
assert_eq!(std::mem::size_of::<Config>(), expected_size);
}