-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathcli.rs
409 lines (376 loc) · 14.7 KB
/
cli.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
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
use clap::{Parser, Subcommand};
use lightning::offers::invoice::Bolt12Invoice;
use lndk::lndk_offers::decode;
use lndk::lndkrpc::offers_client::OffersClient;
use lndk::lndkrpc::{GetInvoiceRequest, PayInvoiceRequest, PayOfferRequest};
use lndk::{
Bolt12InvoiceString, DEFAULT_DATA_DIR, DEFAULT_LNDK_DIR, DEFAULT_RESPONSE_INVOICE_TIMEOUT,
DEFAULT_SERVER_HOST, DEFAULT_SERVER_PORT, TLS_CERT_FILENAME,
};
use std::fs::File;
use std::io::BufReader;
use std::io::Read;
use std::path::PathBuf;
use std::process::exit;
use tonic::transport::{Certificate, Channel, ClientTlsConfig};
use tonic::Request;
fn get_macaroon_path_default(network: &str) -> PathBuf {
home::home_dir()
.unwrap()
.as_path()
.join(format!(".lnd/data/chain/bitcoin/{network}/admin.macaroon"))
}
/// A cli for interacting with lndk.
#[derive(Debug, Parser)]
#[command(name = "lndk-cli")]
#[command(about = "A cli for interacting with lndk", long_about = None)]
struct Cli {
/// Global variables
#[arg(
short,
long,
global = true,
required = false,
default_value = "regtest"
)]
network: String,
#[arg(short, long, global = true, required = false)]
macaroon_path: Option<PathBuf>,
/// A hex-encoded macaroon string to pass in directly to the cli.
#[arg(long, global = true, required = false)]
macaroon_hex: Option<String>,
/// This option is for passing a pem-encoded TLS certificate string to establish a connection
/// with the LNDK server. If this isn't set, the cli will look for the TLS file in the default
/// location (~.lndk/data).
/// Only one of cert_pem or cert_path can be set at once.
#[arg(long, global = true, required = false)]
cert_pem: Option<String>,
/// This option is for passing a file path to a pem-encoded TLS certificate string to establish
/// a connection with the LNDK server. If this isn't set, the cli will look for the TLS file in
/// the default location (~.lndk/data).
/// Only one of cert_pem or cert_path can be set at once.
#[arg(long, global = true, required = false)]
cert_path: Option<PathBuf>,
#[arg(long, global = true, required = false, default_value = format!("https://{DEFAULT_SERVER_HOST}"))]
grpc_host: String,
#[arg(long, global = true, required = false, default_value = DEFAULT_SERVER_PORT.to_string())]
grpc_port: u16,
#[command(subcommand)]
command: Commands,
}
#[derive(Debug, Subcommand)]
enum Commands {
/// Decodes a bech32-encoded offer string into a BOLT 12 offer.
DecodeOffer {
/// The offer string to decode.
offer_string: String,
},
/// Decodes a bech32-encoded invoice string into a BOLT 12 invoice.
DecodeInvoice {
/// The invoice string to decode.
invoice_string: String,
},
/// PayOffer pays a BOLT 12 offer, provided as a 'lno'-prefaced offer string.
PayOffer {
/// The offer string.
offer_string: String,
/// Amount the user would like to pay. If this isn't set, we'll assume the user is paying
/// whatever the offer amount is.
#[arg(required = false)]
amount: Option<u64>,
/// A payer-provided note which will be seen by the recipient.
#[arg(required = false)]
payer_note: Option<String>,
/// The amount of time in seconds that the user would like to wait for an invoice to
/// arrive. If this isn't set, we'll use the default value.
#[arg(long, global = false, required = false, default_value = DEFAULT_RESPONSE_INVOICE_TIMEOUT.to_string())]
response_invoice_timeout: Option<u32>,
},
/// GetInvoice fetch a BOLT 12 invoice, which will be returned as a hex-encoded string. It
/// fetches the invoice from a BOLT 12 offer, provided as a 'lno'-prefaced offer string.
GetInvoice {
/// The offer string.
offer_string: String,
/// Amount the user would like to pay. If this isn't set, we'll assume the user is paying
/// whatever the offer amount is.
#[arg(required = false)]
amount: Option<u64>,
/// A payer-provided note which will be seen by the recipient.
#[arg(required = false)]
payer_note: Option<String>,
/// The amount of time in seconds that the user would like to wait for an invoice to
/// arrive. If this isn't set, we'll use the default value.
#[arg(long, global = false, required = false, default_value = DEFAULT_RESPONSE_INVOICE_TIMEOUT.to_string())]
response_invoice_timeout: Option<u32>,
},
/// PayInvoice pays a hex-encoded BOLT12 invoice.
PayInvoice {
/// The hex-encoded invoice string.
invoice_string: String,
/// Amount the user would like to pay. If this isn't set, we'll assume the user is paying
/// whatever the invoice amount is set to.
#[arg(required = false)]
amount: Option<u64>,
},
}
#[tokio::main]
async fn main() {
let args = Cli::parse();
match args.command {
Commands::DecodeOffer { offer_string } => {
println!("Decoding offer: {offer_string}.");
match decode(offer_string) {
Ok(offer) => {
println!("Decoded offer: {:?}.", offer)
}
Err(e) => {
println!(
"ERROR please provide offer starting with lno. Provided offer is \
invalid, failed to decode with error: {:?}.",
e
);
exit(1)
}
}
}
Commands::DecodeInvoice { invoice_string } => {
println!("Decoding invoice: {invoice_string}.");
let invoice_string: Bolt12InvoiceString = invoice_string.clone().into();
match Bolt12Invoice::try_from(invoice_string) {
Ok(invoice) => {
println!("Decoded invoice: {:?}.", invoice);
}
Err(e) => {
println!(
"ERROR please provide hex-encoded invoice string. Provided invoice is \
invalid, failed to decode with error: {:?}.",
e
);
exit(1);
}
}
}
Commands::PayOffer {
ref offer_string,
amount,
payer_note,
response_invoice_timeout,
} => {
let tls = read_cert_from_args(args.cert_pem, args.cert_path);
let grpc_host = args.grpc_host;
let grpc_port = args.grpc_port;
let channel = Channel::from_shared(format!("{grpc_host}:{grpc_port}"))
.unwrap_or_else(|e| {
println!("ERROR creating endpoint: {e:?}");
exit(1)
})
.tls_config(tls)
.unwrap_or_else(|e| {
println!("ERROR tls config: {e:?}");
exit(1)
})
.connect()
.await
.unwrap_or_else(|e| {
println!("ERROR connecting: {e:?}");
exit(1)
});
let mut client = OffersClient::new(channel);
let offer = match decode(offer_string.to_owned()) {
Ok(offer) => offer,
Err(e) => {
println!(
"ERROR: please provide offer starting with lno. Provided offer is \
invalid, failed to decode with error: {:?}.",
e
);
exit(1)
}
};
let macaroon =
read_macaroon_from_args(args.macaroon_path, args.macaroon_hex, &args.network);
let mut request = Request::new(PayOfferRequest {
offer: offer.to_string(),
amount,
payer_note,
response_invoice_timeout,
});
add_metadata(&mut request, macaroon).unwrap_or_else(|_| exit(1));
match client.pay_offer(request).await {
Ok(_) => println!("Successfully paid for offer!"),
Err(err) => {
println!("Error paying for offer: {err:?}");
exit(1)
}
};
}
Commands::GetInvoice {
ref offer_string,
amount,
payer_note,
response_invoice_timeout,
} => {
let tls = read_cert_from_args(args.cert_pem, args.cert_path);
let grpc_host = args.grpc_host;
let grpc_port = args.grpc_port;
let channel = Channel::from_shared(format!("{grpc_host}:{grpc_port}"))
.unwrap_or_else(|e| {
println!("ERROR creating endpoint: {e:?}");
exit(1)
})
.tls_config(tls)
.unwrap_or_else(|e| {
println!("ERROR tls config: {e:?}");
exit(1)
})
.connect()
.await
.unwrap_or_else(|e| {
println!("ERROR connecting: {e:?}");
exit(1)
});
let mut client = OffersClient::new(channel);
let offer = match decode(offer_string.to_owned()) {
Ok(offer) => offer,
Err(e) => {
println!(
"ERROR: please provide offer starting with lno. Provided offer is \
invalid, failed to decode with error: {:?}.",
e
);
exit(1)
}
};
let macaroon =
read_macaroon_from_args(args.macaroon_path, args.macaroon_hex, &args.network);
let mut request = Request::new(GetInvoiceRequest {
offer: offer.to_string(),
amount,
payer_note,
response_invoice_timeout,
});
add_metadata(&mut request, macaroon).unwrap_or_else(|_| exit(1));
match client.get_invoice(request).await {
Ok(response) => {
println!("Invoice: {:?}.", response.get_ref())
}
Err(err) => {
println!("Error getting invoice for offer: {err:?}");
exit(1)
}
}
}
Commands::PayInvoice {
ref invoice_string,
amount,
} => {
let tls = read_cert_from_args(args.cert_pem, args.cert_path);
let grpc_host = args.grpc_host.clone();
let grpc_port = args.grpc_port;
let channel = Channel::from_shared(format!("{grpc_host}:{grpc_port}"))
.unwrap_or_else(|e| {
println!("ERROR creating endpoint: {e:?}");
exit(1)
})
.tls_config(tls)
.unwrap_or_else(|e| {
println!("ERROR tls config: {e:?}");
exit(1)
})
.connect()
.await
.unwrap_or_else(|e| {
println!("ERROR connecting: {e:?}");
exit(1)
});
let mut client = OffersClient::new(channel);
let macaroon =
read_macaroon_from_args(args.macaroon_path, args.macaroon_hex, &args.network);
let mut request = Request::new(PayInvoiceRequest {
invoice: invoice_string.to_owned(),
amount,
});
add_metadata(&mut request, macaroon).unwrap_or_else(|_| exit(1));
match client.pay_invoice(request).await {
Ok(_) => println!("Successfully paid for offer!"),
Err(err) => {
println!("Error paying invoice: {err:?}");
exit(1)
}
}
}
}
}
fn add_metadata<R>(request: &mut Request<R>, macaroon: String) -> Result<(), ()> {
let macaroon = macaroon.parse().map_err(|e| {
println!("Error parsing provided macaroon string into tonic metadata {e:?}")
})?;
request.metadata_mut().insert("macaroon", macaroon);
Ok(())
}
fn read_macaroon_from_file(path: PathBuf) -> Result<String, std::io::Error> {
let file = File::open(path)?;
let mut mac_contents = BufReader::new(file);
let mut buffer = Vec::new();
mac_contents.read_to_end(&mut buffer)?;
Ok(hex::encode(buffer))
}
fn read_cert_from_args(cert_pem: Option<String>, cert_path: Option<PathBuf>) -> ClientTlsConfig {
// Make sure both cert options are not set.
if cert_path.is_some() && cert_pem.is_some() {
println!("ERROR: Only one of `cert_path` or `cert_pem` should be set.");
exit(1)
}
let pem = match (&cert_pem, &cert_path) {
(Some(pem), _) => pem.clone(),
(None, Some(cert_path)) => std::fs::read_to_string(cert_path).unwrap_or_else(|e| {
println!("ERROR reading cert: {e:?}");
exit(1)
}),
(None, None) => {
// If no cert pem string is provided, we'll look for the tls certificate in the
// default location.
let data_dir = home::home_dir()
.unwrap()
.join(DEFAULT_LNDK_DIR)
.join(DEFAULT_DATA_DIR);
std::fs::read_to_string(data_dir.join(TLS_CERT_FILENAME)).unwrap_or_else(|e| {
println!("ERROR reading cert: {e:?}");
exit(1)
})
}
};
let cert = Certificate::from_pem(pem);
ClientTlsConfig::new()
.ca_certificate(cert)
.domain_name("localhost")
}
fn read_macaroon_from_args(
macaroon_path: Option<PathBuf>,
macaroon_hex: Option<String>,
network: &str,
) -> String {
// Make sure both macaroon options are not set.
if macaroon_path.is_some() && macaroon_hex.is_some() {
println!("ERROR: Only one of `macaroon_path` or `macaroon_hex` should be set.");
exit(1)
}
// Let's grab the macaroon string now. If neither macaroon_path nor macaroon_hex are
// set, use the default macaroon path.
match macaroon_path {
Some(path) => read_macaroon_from_file(path.clone()).unwrap_or_else(|e| {
println!("ERROR reading macaroon from file {e:?}");
exit(1)
}),
None => match &macaroon_hex {
Some(macaroon) => macaroon.clone(),
None => {
let path = get_macaroon_path_default(network);
read_macaroon_from_file(path).unwrap_or_else(|e| {
println!("ERROR reading macaroon from file {e:?}");
exit(1)
})
}
},
}
}