-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathargs.rs
202 lines (180 loc) · 6.74 KB
/
args.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
// Modern, minimalistic & standard-compliant cold wallet library.
//
// SPDX-License-Identifier: Apache-2.0
//
// Written in 2020-2024 by
// Dr Maxim Orlovsky <[email protected]>
//
// Copyright (C) 2020-2024 LNP/BP Standards Association. All rights reserved.
// Copyright (C) 2020-2024 Dr Maxim Orlovsky. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fmt::Debug;
use std::path::PathBuf;
use std::process::exit;
use std::sync::OnceLock;
use bpstd::XpubDerivable;
use clap::Subcommand;
use descriptors::Descriptor;
use strict_encoding::Ident;
use crate::cli::{
Config, DescrStdOpts, DescriptorOpts, ExecError, GeneralOpts, ResolverOpt, WalletOpts,
};
use crate::indexers::electrum::ElectrumClient;
use crate::indexers::esplora;
use crate::{AnyIndexer, MayError, Wallet};
/// Command-line arguments
#[derive(Parser)]
#[derive(Clone, Eq, PartialEq, Debug)]
#[command(author, version, about)]
pub struct Args<C: Clone + Eq + Debug + Subcommand, O: DescriptorOpts = DescrStdOpts> {
/// Set verbosity level.
///
/// Can be used multiple times to increase verbosity.
#[clap(short, long, global = true, action = clap::ArgAction::Count)]
pub verbose: u8,
#[command(flatten)]
pub wallet: WalletOpts<O>,
#[command(flatten)]
pub resolver: ResolverOpt,
/// Force-sync wallet data with the indexer before performing the operation.
#[clap(long, global = true)]
pub sync: bool,
#[command(flatten)]
pub general: GeneralOpts,
/// Command to execute.
#[clap(subcommand)]
pub command: C,
}
impl<C: Clone + Eq + Debug + Subcommand, O: DescriptorOpts> Args<C, O> {
pub fn translate<C1: Clone + Eq + Debug + Subcommand>(&self, cmd: &C1) -> Args<C1, O> {
Args {
verbose: self.verbose,
wallet: self.wallet.clone(),
resolver: self.resolver.clone(),
sync: self.sync,
general: self.general.clone(),
command: cmd.clone(),
}
}
}
pub trait Exec {
type Error: std::error::Error;
const CONF_FILE_NAME: &'static str;
fn exec(self, config: Config, name: &'static str) -> Result<(), Self::Error>;
}
impl<C: Clone + Eq + Debug + Subcommand, O: DescriptorOpts> Args<C, O> {
pub fn process(&mut self) { self.general.process(); }
pub fn conf_path(&self, name: &'static str) -> PathBuf {
let mut conf_path = self.general.base_dir();
conf_path.push(name);
conf_path.set_extension("toml");
conf_path
}
pub fn indexer(&self) -> Result<AnyIndexer, ExecError> {
use crate::indexers::IndexerCache;
// Define a static variable to store IndexerCache,
// Ensuring that all cached data is centralized
// Initialize only once
static INDEXER_CACHE: OnceLock<IndexerCache> = OnceLock::new();
let indexer_cache = INDEXER_CACHE
.get_or_init(|| {
IndexerCache::new(
self.general
.indexer_cache_factor
.try_into()
.expect("Error: indexer cache size is invalid"),
)
})
.clone();
let network = self.general.network.to_string();
Ok(match (&self.resolver.esplora, &self.resolver.electrum, &self.resolver.mempool) {
(None, Some(url), None) => {
AnyIndexer::Electrum(Box::new(ElectrumClient::new(url, indexer_cache)?))
}
(Some(url), None, None) => AnyIndexer::Esplora(Box::new(esplora::Client::new_esplora(
&url.replace("{network}", &network),
indexer_cache,
)?)),
(None, None, Some(url)) => AnyIndexer::Mempool(Box::new(esplora::Client::new_mempool(
&url.replace("{network}", &network),
indexer_cache,
)?)),
_ => {
eprintln!(
"Error: no blockchain indexer specified; use either --esplora --mempool or \
--electrum argument"
);
exit(1);
}
})
}
#[allow(clippy::multiple_bound_locations)]
pub fn bp_wallet<D: Descriptor>(
&self,
conf: &Config,
) -> Result<Wallet<XpubDerivable, D>, ExecError>
where
for<'de> D: From<O::Descr> + serde::Serialize + serde::Deserialize<'de>,
{
eprint!("Loading descriptor");
let mut sync = self.sync || self.wallet.descriptor_opts.is_some();
let mut wallet: Wallet<XpubDerivable, D> =
if let Some(d) = self.wallet.descriptor_opts.descriptor() {
eprintln!(" from command-line argument");
eprint!("Syncing");
Wallet::new_layer1(d.into(), self.general.network)
} else {
let path = if let Some(wallet_path) = self.wallet.wallet_path.clone() {
eprint!(" from specified wallet directory ... ");
wallet_path
} else {
let wallet_name = self
.wallet
.name
.as_ref()
.map(Ident::to_string)
.unwrap_or(conf.default_wallet.clone());
eprint!(" from wallet {wallet_name} ... ");
self.general.wallet_dir(wallet_name)
};
let (wallet, warnings) = Wallet::load(&path, true)?;
if warnings.is_empty() {
eprintln!("success");
} else {
eprintln!("complete with warnings:");
for warning in warnings {
eprintln!("- {warning}");
}
sync = true;
}
wallet
};
if sync {
let indexer = self.indexer()?;
eprint!("Syncing");
if let MayError {
err: Some(errors), ..
} = wallet.update(&indexer)
{
eprintln!(" partial, some requests has failed:");
for err in errors {
eprintln!("- {err}");
}
} else {
eprintln!(" success");
}
}
Ok(wallet)
}
}