-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathmain.rs
More file actions
366 lines (311 loc) · 10.9 KB
/
main.rs
File metadata and controls
366 lines (311 loc) · 10.9 KB
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
//! Command-line interface for the Dash SPV client.
use std::path::PathBuf;
use std::process;
use std::sync::Arc;
use clap::{Parser, ValueEnum};
use dash_spv::network::NetworkEvent;
use dash_spv::sync::{SyncEvent, SyncProgress};
use dash_spv::{ClientConfig, DashSpvClient, EventHandler, LevelFilter, MempoolStrategy, Network};
use key_wallet::wallet::managed_wallet_info::ManagedWalletInfo;
use key_wallet_manager::{WalletEvent, WalletManager};
use tokio_util::sync::CancellationToken;
/// Network selection for CLI
#[derive(Clone, Copy, Debug, ValueEnum)]
enum NetworkArg {
Mainnet,
Testnet,
Regtest,
}
impl From<NetworkArg> for Network {
fn from(arg: NetworkArg) -> Self {
match arg {
NetworkArg::Mainnet => Network::Mainnet,
NetworkArg::Testnet => Network::Testnet,
NetworkArg::Regtest => Network::Regtest,
}
}
}
/// Validation mode selection for CLI
#[derive(Clone, Copy, Debug, ValueEnum)]
enum ValidationModeArg {
None,
Basic,
Full,
}
impl From<ValidationModeArg> for dash_spv::ValidationMode {
fn from(arg: ValidationModeArg) -> Self {
match arg {
ValidationModeArg::None => dash_spv::ValidationMode::None,
ValidationModeArg::Basic => dash_spv::ValidationMode::Basic,
ValidationModeArg::Full => dash_spv::ValidationMode::Full,
}
}
}
/// Log level selection for CLI
#[derive(Clone, Copy, Debug, ValueEnum)]
#[value(rename_all = "lowercase")]
enum LogLevelArg {
Error,
Warn,
Info,
Debug,
Trace,
}
impl From<LogLevelArg> for LevelFilter {
fn from(arg: LogLevelArg) -> Self {
match arg {
LogLevelArg::Error => LevelFilter::ERROR,
LogLevelArg::Warn => LevelFilter::WARN,
LogLevelArg::Info => LevelFilter::INFO,
LogLevelArg::Debug => LevelFilter::DEBUG,
LogLevelArg::Trace => LevelFilter::TRACE,
}
}
}
/// Logs all SPV client events via tracing.
struct LoggingEventHandler;
impl EventHandler for LoggingEventHandler {
fn on_sync_event(&self, event: &SyncEvent) {
tracing::info!("{}", event.description());
}
fn on_network_event(&self, event: &NetworkEvent) {
tracing::info!("{}", event.description());
}
fn on_progress(&self, progress: &SyncProgress) {
tracing::info!("Sync progress: {}", progress);
}
fn on_wallet_event(&self, event: &WalletEvent) {
tracing::info!("Wallet: {}", event.description());
}
fn on_error(&self, error: &str) {
tracing::error!("{}", error);
}
}
/// Dash SPV (Simplified Payment Verification) client
#[derive(Parser, Debug)]
#[command(name = "dash-spv", version = dash_spv::VERSION, about)]
struct Args {
/// Network to connect to
#[arg(short, long, value_enum, default_value = "mainnet")]
network: NetworkArg,
/// Data directory for storage (default: unique directory in /tmp)
#[arg(short, long)]
data_dir: Option<PathBuf>,
/// Peer address to connect to (can be used multiple times)
#[arg(short, long, value_name = "ADDRESS")]
peer: Vec<String>,
/// Log level (CLI overrides RUST_LOG env var)
#[arg(short, long, value_enum, env = "RUST_LOG", default_value = "info")]
log_level: LogLevelArg,
/// Disable BIP157 filter synchronization
#[arg(long)]
no_filters: bool,
/// Disable masternode list synchronization
#[arg(long)]
no_masternodes: bool,
/// Disable mempool transaction tracking
#[arg(long)]
no_mempool: bool,
/// Mempool strategy: fetch-all (higher bandwidth / more privacy) or bloom-filter (efficient / less privacy)
#[arg(long, value_enum, default_value = "bloom-filter")]
mempool_strategy: MempoolStrategy,
/// Validation mode
#[arg(long, value_enum, default_value = "full")]
validation_mode: ValidationModeArg,
/// Start syncing from a specific block height using the nearest checkpoint.
/// Use 'now' for the latest checkpoint.
#[arg(short, long, value_name = "HEIGHT")]
start_height: Option<String>,
/// Disable log file output (enables console logging as fallback)
#[arg(long)]
no_log_file: bool,
/// Print logs to the console
#[arg(long)]
print_to_console: bool,
/// Directory for log files (default: <data-dir>/logs)
#[arg(long)]
log_dir: Option<PathBuf>,
/// Maximum number of archived log files to keep
#[arg(long, default_value = "20")]
max_log_files: usize,
/// Path to file containing BIP39 mnemonic phrase
#[arg(long, value_name = "PATH")]
mnemonic_file: String,
}
#[tokio::main]
async fn main() {
if let Err(e) = run().await {
eprintln!("Error: {}", e);
// Provide specific exit codes for different error types
let exit_code = if let Some(spv_error) = e.downcast_ref::<dash_spv::SpvError>() {
match spv_error {
dash_spv::SpvError::Network(_) => 1,
dash_spv::SpvError::Storage(_) => 2,
dash_spv::SpvError::Config(_) => 3,
_ => 255,
}
} else {
255
};
process::exit(exit_code);
}
}
async fn run() -> Result<(), Box<dyn std::error::Error>> {
let args = Args::parse();
let network: Network = args.network.into();
let validation_mode: dash_spv::ValidationMode = args.validation_mode.into();
let log_level: LevelFilter = args.log_level.into();
let mnemonic_phrase = std::fs::read_to_string(&args.mnemonic_file)
.map_err(|e| format!("Failed to read mnemonic file '{}': {}", args.mnemonic_file, e))?
.trim()
.to_string();
// Create data directory
let data_dir = args.data_dir.clone().unwrap_or_else(|| {
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let pid = std::process::id();
let dir_name = format!("dash-spv-{}-{}", timestamp, pid);
std::env::temp_dir().join(dir_name)
});
// Configure logging
let log_dir = args.log_dir.clone().unwrap_or_else(|| data_dir.join("logs"));
let file_config = if !args.no_log_file {
Some(dash_spv::LogFileConfig {
log_dir,
max_files: args.max_log_files,
})
} else {
None
};
let console_enabled = args.no_log_file || args.print_to_console;
let logging_config = dash_spv::LoggingConfig {
level: Some(log_level),
console: console_enabled,
file: file_config,
thread_local: false,
};
// Initialize logging, keep guard alive for the duration of run()
let _logging_guard = dash_spv::init_logging(logging_config)?;
tracing::info!("Starting Dash SPV client");
tracing::info!("Network: {:?}", network);
tracing::info!("Data directory: {}", data_dir.display());
tracing::info!("Validation mode: {:?}", validation_mode);
// Create configuration
let mut config = ClientConfig::new(network)
.with_storage_path(data_dir.clone())
.with_validation_mode(validation_mode);
// Add custom peers if specified
if !args.peer.is_empty() {
config.peers.clear();
for peer in &args.peer {
match peer.parse() {
Ok(addr) => config.add_peer(addr),
Err(e) => {
tracing::error!("Invalid peer address '{}': {}", peer, e);
process::exit(1);
}
};
}
}
// Configure features
if args.no_filters {
config = config.without_filters();
}
if args.no_masternodes {
config = config.without_masternodes();
}
if args.no_mempool {
config.enable_mempool_tracking = false;
} else {
config = config.with_mempool_tracking(args.mempool_strategy);
}
// Set start height if specified
if let Some(ref start_height_str) = args.start_height {
if start_height_str == "now" {
// Use a very high number to get the latest checkpoint
config.start_from_height = Some(u32::MAX);
tracing::info!("Will start syncing from the latest available checkpoint");
} else {
let start_height = start_height_str
.parse::<u32>()
.map_err(|e| format!("Invalid start height '{}': {}", start_height_str, e))?;
config.start_from_height = Some(start_height);
tracing::info!("Will start syncing from height: {}", start_height);
}
}
// Validate configuration
if let Err(e) = config.validate() {
tracing::error!("Configuration error: {}", e);
process::exit(1);
}
// Create the wallet manager
let mut wallet_manager = WalletManager::<ManagedWalletInfo>::new(config.network);
wallet_manager.create_wallet_from_mnemonic(
mnemonic_phrase.as_str(),
0,
key_wallet::wallet::initialization::WalletAccountCreationOptions::default(),
)?;
let wallet = Arc::new(tokio::sync::RwLock::new(wallet_manager));
// Create network manager
let network_manager = match dash_spv::network::manager::PeerNetworkManager::new(&config).await {
Ok(nm) => nm,
Err(e) => {
eprintln!("Failed to create network manager: {}", e);
process::exit(1);
}
};
let storage_manager = match dash_spv::storage::DiskStorageManager::new(&config).await {
Ok(sm) => sm,
Err(e) => {
eprintln!("Failed to create disk storage manager: {}", e);
process::exit(1);
}
};
run_client(config, network_manager, storage_manager, wallet).await?;
Ok(())
}
async fn run_client<S: dash_spv::storage::StorageManager>(
config: ClientConfig,
network_manager: dash_spv::network::manager::PeerNetworkManager,
storage_manager: S,
wallet: Arc<tokio::sync::RwLock<WalletManager<ManagedWalletInfo>>>,
) -> Result<(), Box<dyn std::error::Error>> {
// Create and start the client
let client = match DashSpvClient::<
WalletManager<ManagedWalletInfo>,
dash_spv::network::manager::PeerNetworkManager,
S,
>::new(
config.clone(),
network_manager,
storage_manager,
wallet.clone(),
vec![Arc::new(LoggingEventHandler)],
)
.await
{
Ok(client) => client,
Err(e) => {
eprintln!("Failed to create SPV client: {}", e);
process::exit(1);
}
};
let shutdown_token = CancellationToken::new();
let ctrl_c_token = shutdown_token.clone();
tokio::spawn(async move {
tokio::select! {
result = tokio::signal::ctrl_c() => {
result.ok();
tracing::debug!("Shutdown signal received");
}
_ = ctrl_c_token.cancelled() => {
tracing::debug!("Shutdown token cancelled");
}
}
ctrl_c_token.cancel();
});
client.run(shutdown_token).await?;
Ok(())
}