-
-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathmain.rs
More file actions
226 lines (197 loc) · 7.82 KB
/
main.rs
File metadata and controls
226 lines (197 loc) · 7.82 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
#[allow(dead_code)]
mod args;
use std::fs::File;
use std::fs::OpenOptions;
use std::io::Read;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Arc;
use radicle_term as term;
use lampo_bdk_wallet::BDKWalletManager;
use lampo_chain::LampoChainSync;
use lampo_common::backend::Backend;
use lampo_common::conf::LampoConf;
use lampo_common::error;
use lampo_common::logger;
use lampo_httpd::handler::HttpdHandler;
use lampod::chain::WalletManager;
use lampod::LampoDaemon;
use crate::args::LampoCliArgs;
#[tokio::main]
async fn main() -> error::Result<()> {
log::debug!("Started!");
let args = args::parse_args()?;
match &args.subcommand {
Some(crate::args::LampoCliSubcommand::NewWallet) => {
// Prepare minimal config for wallet creation (no logger needed)
let mut lampo_conf: LampoConf = args.clone().try_into()?;
lampo_conf
.ldk_conf
.channel_handshake_limits
.force_announced_channel_preference = false;
let lampo_conf = Arc::new(lampo_conf);
let client = lampo_conf.node.clone();
let client: Arc<dyn Backend> = match client.as_str() {
"core" => Arc::new(LampoChainSync::new(lampo_conf.clone())?),
_ => error::bail!("client {:?} not supported", client),
};
let words_path = format!("{}/", lampo_conf.path());
create_new_wallet(lampo_conf, client, &words_path).await?;
return Ok(());
}
_ => run(args).await,
}
}
fn write_words_to_file<P: AsRef<Path>>(path: P, words: String) -> error::Result<()> {
let mut file = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(path)?;
// FIXME: we should give the possibility to encrypt this file.
file.write_all(words.as_bytes())?;
Ok(())
}
fn load_words_from_file<P: AsRef<Path>>(path: P) -> error::Result<String> {
let mut file = File::open(path.as_ref())?;
let mut content = String::new();
file.read_to_string(&mut content)?;
if content.is_empty() {
let path = path.as_ref().to_string_lossy().to_string();
error::bail!("The content of the wallet located at `{path}`. You lost the secret? Please report a bug this should never happens")
} else {
Ok(content)
}
}
async fn create_new_wallet(
lampo_conf: Arc<LampoConf>,
client: Arc<dyn Backend>,
words_path: &str,
) -> error::Result<Arc<dyn WalletManager>> {
let (wallet, mnemonic) = match client.kind() {
lampo_common::backend::BackendKind::Core => {
BDKWalletManager::new(lampo_conf.clone()).await?
}
};
write_words_to_file(format!("{}/wallet.dat", words_path), mnemonic.clone())?;
println!("Your new wallet mnemonic is:\n{mnemonic}\nPLEASE BACK IT UP SECURELY!");
Ok(Arc::new(wallet))
}
/// Return the root directory.
async fn run(args: LampoCliArgs) -> error::Result<()> {
let restore_wallet = args.restore_wallet;
// After this point the configuration is ready!
let mut lampo_conf: LampoConf = args.try_into()?;
log::debug!(target: "lampod-cli", "init wallet ..");
// init the logger here
logger::init(
&lampo_conf.log_level,
lampo_conf
.log_file
.as_ref()
.and_then(|path| Some(PathBuf::from_str(&path).unwrap())),
)
.expect("unable to init the logger for the first time");
lampo_conf
.ldk_conf
.channel_handshake_limits
.force_announced_channel_preference = false;
let lampo_conf = Arc::new(lampo_conf);
// Prepare the backend
let client = lampo_conf.node.clone();
log::debug!(target: "lampod-cli", "lampo running with `{client}` backend");
let client: Arc<dyn Backend> = match client.as_str() {
"core" => Arc::new(LampoChainSync::new(lampo_conf.clone())?),
_ => error::bail!("client {:?} not supported", client),
};
let words_path = format!("{}/", lampo_conf.path());
let wallet = if restore_wallet {
if Path::new(&format!("{}/wallet.dat", words_path)).exists() {
// Load the mnemonic from the file
let mnemonic = load_words_from_file(format!("{}/wallet.dat", words_path))?;
let wallet = match client.kind() {
lampo_common::backend::BackendKind::Core => {
BDKWalletManager::restore(lampo_conf.clone(), &mnemonic).await?
}
};
wallet
} else {
// If file doesn't exist, ask for user input
let mnemonic: String = term::input(
"BIP 39 Mnemonic",
None,
Some("To restore the wallet, lampo needs the BIP39 mnemonic with words separated by spaces."),
)?;
// FIXME: make some sanity check about the mnemonic string
let wallet = match client.kind() {
lampo_common::backend::BackendKind::Core => {
// SAFETY: It is safe to unwrap the mnemonic because we check it
// before.
BDKWalletManager::restore(lampo_conf.clone(), &mnemonic).await?
}
};
write_words_to_file(format!("{}/wallet.dat", words_path), mnemonic)?;
wallet
}
} else {
if Path::new(&format!("{}/wallet.dat", words_path)).exists() {
// Load the mnemonic from the file
log::warn!("Loading from existing wallet");
let mnemonic = load_words_from_file(format!("{}/wallet.dat", words_path))?;
let wallet = match client.kind() {
lampo_common::backend::BackendKind::Core => {
BDKWalletManager::restore(lampo_conf.clone(), &mnemonic).await?
}
};
wallet
} else {
// Use the new function for wallet creation
create_new_wallet(lampo_conf.clone(), client.clone(), &words_path).await?;
return Ok(());
}
};
let wallet = Arc::new(wallet);
log::debug!(target: "lampod-cli", "wallet created with success");
let mut lampod = LampoDaemon::new(lampo_conf.clone(), wallet.clone());
// Do wallet syncing in the background!
wallet.listen().await?;
// Init the lampod
lampod.init(client).await?;
log::debug!(target: "lampod-cli", "Lampo directory `{}`", lampo_conf.path());
let mut _pid = filelock_rs::pid::Pid::new(lampo_conf.path(), "lampod".to_owned())
.map_err(|err| {
log::error!("{err}");
error::anyhow!("impossible take a lock on the `lampod.pid` file, maybe there is another instance running?")
})?;
let lampod = Arc::new(lampod);
run_httpd(lampod.clone()).await?;
let handler = Arc::new(HttpdHandler::new(format!(
"{}:{}",
lampo_conf.api_host, lampo_conf.api_port
))?);
lampod.add_external_handler(handler).await?;
// Handle the shutdown signal and pass down to the lampod.listen()
ctrlc::set_handler(move || {
use std::time::Duration;
log::info!("Shutdown...");
std::thread::sleep(Duration::from_secs(5));
std::process::exit(0);
})?;
log::info!(target: "lampod-cli", "------------ Starting Server ------------");
lampod.listen().await??;
Ok(())
}
pub async fn run_httpd(lampod: Arc<LampoDaemon>) -> error::Result<()> {
let url = format!("{}:{}", lampod.conf().api_host, lampod.conf().api_port);
let mut http_hosting = url.clone();
if let Some(clean_url) = url.strip_prefix("http://") {
http_hosting = clean_url.to_string();
} else if let Some(clean_url) = url.strip_prefix("https://") {
http_hosting = clean_url.to_string();
}
log::info!("preparing httpd api on addr `{url}`");
tokio::spawn(lampo_httpd::run(lampod, http_hosting, url));
Ok(())
}