-
Notifications
You must be signed in to change notification settings - Fork 210
/
main.rs
602 lines (543 loc) · 17.5 KB
/
main.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
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
use std::collections::HashMap;
use std::env;
use std::future::Future;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Arc;
use std::time::{Duration, Instant};
use anyhow::{Context, Result};
use bitcoin::hashes::hex::ToHex;
use bitcoincore_rpc::{bitcoin, RpcApi};
use cln_rpc::ClnRpc;
use federation::{run_dkg, Federation};
use fedimint_client::module::gen::{ClientModuleGenRegistry, DynClientModuleGen};
use fedimint_core::config::load_from_file;
use fedimint_core::db::Database;
use fedimint_core::encoding::Encodable;
use fedimint_core::task::TaskGroup;
use fedimint_ln_client::LightningClientGen;
use fedimint_wallet_client::WalletClientGen;
use mint_client::modules::mint::MintClientGen;
use mint_client::{module_decode_stubs, UserClient, UserClientConfig};
use tokio::fs;
use tokio::sync::{MappedMutexGuard, Mutex, MutexGuard};
use tokio::time::sleep;
use tonic_lnd::lnrpc::GetInfoRequest;
use tracing::{info, warn};
mod util;
use util::*;
#[derive(Clone)]
pub struct Bitcoind {
client: Arc<bitcoincore_rpc::Client>,
_process: ProcessHandle,
}
impl Bitcoind {
pub async fn new(processmgr: &ProcessManager) -> Result<Self> {
let btc_dir = env::var("FM_BTC_DIR")?;
let process = processmgr
.spawn_daemon("bitcoind", cmd!("bitcoind", "-datadir={btc_dir}"))
.await?;
let url = env::var("FM_TEST_BITCOIND_RPC")?.parse()?;
let (host, auth) = fedimint_bitcoind::bitcoincore_rpc::from_url_to_url_auth(&url)?;
let client = Arc::new(bitcoincore_rpc::Client::new(&host, auth)?);
Self::init(&client).await?;
Ok(Self {
_process: process,
client,
})
}
async fn init(client: &bitcoincore_rpc::Client) -> Result<()> {
// create RPC wallet
while let Err(e) = client.create_wallet("", None, None, None, None) {
if e.to_string().contains("Database already exists") {
break;
}
warn!("Failed to create wallet ... retrying {}", e);
sleep(Duration::from_secs(1)).await
}
// mine blocks
let address = client.get_new_address(None, None)?;
client.generate_to_address(101, &address)?;
// wait bitciond is ready
poll("bitcoind", || async {
Ok(client
.get_blockchain_info()
.map_or(false, |info| (info.blocks > 100)))
})
.await?;
Ok(())
}
pub fn client(&self) -> Arc<bitcoincore_rpc::Client> {
self.client.clone()
}
pub async fn mine_blocks(&self, amt: u64) -> Result<()> {
let client = self.client();
let addr = client.get_new_address(None, None)?;
client.generate_to_address(amt, &addr)?;
Ok(())
}
pub async fn send_to(&self, addr: String, amt: u64) -> Result<bitcoin::Txid> {
let amt = bitcoin::Amount::from_sat(amt);
let tx = self.client().send_to_address(
&bitcoin::Address::from_str(&addr)?,
amt,
None,
None,
None,
None,
None,
None,
)?;
Ok(tx)
}
pub async fn get_txout_proof(&self, txid: &bitcoin::Txid) -> Result<String> {
let proof = self.client().get_tx_out_proof(&[*txid], None)?;
Ok(proof.to_hex())
}
pub async fn get_raw_transaction(&self, txid: &bitcoin::Txid) -> Result<String> {
let tx = self.client().get_raw_transaction(txid, None)?;
let bytes = tx.consensus_encode_to_vec()?;
Ok(bytes.to_hex())
}
}
#[derive(Clone)]
pub struct Lightningd {
rpc: Arc<Mutex<ClnRpc>>,
_process: ProcessHandle,
bitcoind: Bitcoind,
}
impl Lightningd {
pub async fn new(process_mgr: &ProcessManager, bitcoind: Bitcoind) -> Result<Self> {
let cln_dir = env::var("FM_CLN_DIR")?;
let bin_dir = env::var("FM_BIN_DIR")?;
let cmd = cmd!(
"lightningd",
"--dev-fast-gossip",
"--dev-bitcoind-poll=1",
"--lightning-dir={cln_dir}",
"--plugin={bin_dir}/gateway-cln-extension"
);
let process = process_mgr.spawn_daemon("lightningd", cmd).await?;
let socket_cln = PathBuf::from(cln_dir).join("regtest/lightning-rpc");
poll("lightningd", || async {
Ok(fs::try_exists(&socket_cln).await?)
})
.await?;
let rpc = ClnRpc::new(socket_cln).await?;
Ok(Self {
bitcoind,
rpc: Arc::new(Mutex::new(rpc)),
_process: process,
})
}
pub async fn request<R: cln_rpc::model::IntoRequest>(&self, request: R) -> Result<R::Response>
where
R::Response: Send,
{
let mut rpc = self.rpc.lock().await;
Ok(rpc.call_typed(request).await?)
}
pub async fn await_block_processing(&self) -> Result<()> {
poll("lightningd block processing", || async {
let btc_height = self.bitcoind.client().get_blockchain_info()?.blocks;
let lnd_height = self
.request(cln_rpc::model::GetinfoRequest {})
.await?
.blockheight;
Ok((lnd_height as u64) == btc_height)
})
.await?;
Ok(())
}
pub async fn pub_key(&self) -> Result<String> {
Ok(self
.request(cln_rpc::model::GetinfoRequest {})
.await?
.id
.to_string())
}
}
#[derive(Clone)]
pub struct Lnd {
client: Arc<Mutex<tonic_lnd::LndClient>>,
_process: ProcessHandle,
_bitcoind: Bitcoind,
}
impl Lnd {
pub async fn new(process_mgr: &ProcessManager, bitcoind: Bitcoind) -> Result<Self> {
let lnd_dir = env::var("FM_LND_DIR")?;
let cmd = cmd!("lnd", "--lnddir={lnd_dir}");
let process = process_mgr.spawn_daemon("lnd", cmd).await?;
let lnd_rpc_addr = env::var("FM_LND_RPC_ADDR")?;
let lnd_macaroon = env::var("FM_LND_MACAROON")?;
let lnd_tls_cert = env::var("FM_LND_TLS_CERT")?;
poll("lnd", || async {
Ok(fs::try_exists(&lnd_tls_cert).await? && fs::try_exists(&lnd_macaroon).await?)
})
.await?;
let client = tonic_lnd::connect(
lnd_rpc_addr.clone(),
lnd_tls_cert.clone(),
lnd_macaroon.clone(),
)
.await?;
Ok(Self {
_bitcoind: bitcoind,
client: Arc::new(Mutex::new(client)),
_process: process,
})
}
pub async fn client_lock(&self) -> Result<MappedMutexGuard<'_, tonic_lnd::LightningClient>> {
let guard = self.client.lock().await;
Ok(MutexGuard::map(guard, |client| client.lightning()))
}
pub async fn pub_key(&self) -> Result<String> {
Ok(self
.client_lock()
.await?
.get_info(GetInfoRequest {})
.await?
.into_inner()
.identity_pubkey)
}
pub async fn await_block_processing(&self) -> Result<()> {
poll("lnd block processing", || async {
Ok(self
.client_lock()
.await?
.get_info(GetInfoRequest {})
.await?
.into_inner()
.synced_to_chain)
})
.await?;
Ok(())
}
}
pub async fn open_channel(bitcoind: &Bitcoind, cln: &Lightningd, lnd: &Lnd) -> Result<()> {
tokio::try_join!(cln.await_block_processing(), lnd.await_block_processing())?;
info!("block sync done");
let cln_addr = cln
.request(cln_rpc::model::NewaddrRequest { addresstype: None })
.await?
.bech32
.context("bech32 should be present")?;
bitcoind.send_to(cln_addr, 100_000_000).await?;
bitcoind.mine_blocks(10).await?;
let lnd_pubkey = lnd.pub_key().await?;
cln.request(cln_rpc::model::ConnectRequest {
id: lnd_pubkey.parse()?,
host: Some("127.0.0.1".to_owned()),
port: Some(9734),
})
.await?;
poll("fund channel", || async {
Ok(cln
.request(cln_rpc::model::FundchannelRequest {
id: lnd_pubkey.parse()?,
amount: cln_rpc::primitives::AmountOrAll::Amount(
cln_rpc::primitives::Amount::from_sat(10_000_000),
),
push_msat: Some(cln_rpc::primitives::Amount::from_sat(5_000_000)),
feerate: None,
announce: None,
minconf: None,
close_to: None,
request_amt: None,
compact_lease: None,
utxos: None,
mindepth: None,
reserve: None,
})
.await
.is_ok())
})
.await?;
poll("list peers", || async {
Ok(!cln
.request(cln_rpc::model::ListpeersRequest {
id: Some(lnd_pubkey.parse()?),
level: None,
})
.await?
.peers
.is_empty())
})
.await?;
bitcoind.mine_blocks(10).await?;
Ok(())
}
#[derive(Clone)]
pub enum ClnOrLnd {
Cln(Lightningd),
Lnd(Lnd),
}
impl ClnOrLnd {
fn name(&self) -> &'static str {
match self {
ClnOrLnd::Cln(_) => "cln",
ClnOrLnd::Lnd(_) => "lnd",
}
}
}
#[derive(Clone)]
pub struct Gatewayd {
_process: ProcessHandle,
ln: ClnOrLnd,
}
impl Gatewayd {
pub async fn new(process_mgr: &ProcessManager, ln: ClnOrLnd) -> Result<Self> {
let bin_dir = env::var("FM_BIN_DIR")?;
let ln_name = ln.name();
let test_dir = env::var("FM_TEST_DIR")?;
let gateway_env = match ln {
ClnOrLnd::Cln(_) => HashMap::from_iter([
(
"FM_GATEWAY_DATA_DIR".to_owned(),
format!("{test_dir}/gw-cln"),
),
(
"FM_GATEWAY_LISTEN_ADDR".to_owned(),
"127.0.0.1:8175".to_owned(),
),
(
"FM_GATEWAY_API_ADDR".to_owned(),
"http://127.0.0.1:8175".to_owned(),
),
]),
ClnOrLnd::Lnd(_) => HashMap::from_iter([
(
"FM_GATEWAY_DATA_DIR".to_owned(),
format!("{test_dir}/gw-lnd"),
),
(
"FM_GATEWAY_LISTEN_ADDR".to_owned(),
"127.0.0.1:28175".to_owned(),
),
(
"FM_GATEWAY_API_ADDR".to_owned(),
"http://127.0.0.1:28175".to_owned(),
),
]),
};
let process = process_mgr
.spawn_daemon(
&format!("gatewayd-{ln_name}"),
cmd!("{bin_dir}/gatewayd", ln_name).envs(gateway_env),
)
.await?;
Ok(Self {
ln,
_process: process,
})
}
pub async fn cmd(&self) -> Command {
let bin_dir = env::var("FM_BIN_DIR").expect("FM_BIN_DIR not found");
match &self.ln {
ClnOrLnd::Cln(_) => {
cmd!("{bin_dir}/gateway-cli", "--rpcpassword=theresnosecondbest")
}
ClnOrLnd::Lnd(_) => {
cmd!(
"{bin_dir}/gateway-cli",
"--rpcpassword=theresnosecondbest",
"-a",
"http://127.0.0.1:28175"
)
}
}
}
pub async fn connect_fed(&self, fed: &Federation) -> Result<()> {
let connect_str = poll_value("connect info", || async {
match cmd!(fed, "connect-info").out_json().await {
Ok(info) => Ok(Some(
info["connect_info"]
.as_str()
.context("connect_info must be string")?
.to_owned(),
)),
Err(_) => Ok(None),
}
})
.await?;
poll("gateway connect-fed", || async {
Ok(cmd!(self, "connect-fed", connect_str.clone())
.run()
.await
.is_ok())
})
.await?;
Ok(())
}
}
mod federation;
async fn latency_tests(dev_fed: DevFed) -> Result<()> {
#[allow(unused_variables)]
let DevFed {
bitcoind,
cln,
lnd,
fed,
gw_cln,
gw_lnd,
} = dev_fed;
fed.pegin(10_000_000).await?;
let iterations = 10;
let start_time = Instant::now();
for _ in 0..iterations {
let notes = cmd!(fed, "spend", "50000").out_json().await?["note"]
.as_str()
.context("note must be a string")?
.to_owned();
cmd!(fed, "reissue", notes).run().await?;
cmd!(fed, "fetch").run().await?;
}
let reissue_time = start_time.elapsed().as_secs_f64() / (iterations as f64);
let start_time = Instant::now();
for _ in 0..iterations {
let add_invoice = lnd
.client_lock()
.await?
.add_invoice(tonic_lnd::lnrpc::Invoice {
value_msat: 100_000,
..Default::default()
})
.await?
.into_inner();
let invoice = add_invoice.payment_request;
let payment_hash = add_invoice.r_hash;
cmd!(fed, "ln-pay", invoice).run().await?;
let invoice_status = lnd
.client_lock()
.await?
.lookup_invoice(tonic_lnd::lnrpc::PaymentHash {
r_hash: payment_hash,
..Default::default()
})
.await?
.into_inner()
.state();
anyhow::ensure!(invoice_status == tonic_lnd::lnrpc::invoice::InvoiceState::Settled);
}
let ln_send_time = start_time.elapsed().as_secs_f64() / (iterations as f64);
let start_time = Instant::now();
for _ in 0..iterations {
let invoice = cmd!(fed, "ln-invoice", "100000msat", "incoming-over-lnd-gw")
.out_json()
.await?["invoice"]
.as_str()
.context("invoice must be string")?
.to_owned();
let payment = lnd
.client_lock()
.await?
.send_payment_sync(tonic_lnd::lnrpc::SendRequest {
payment_request: invoice,
..Default::default()
})
.await?
.into_inner();
let payment_status = lnd
.client_lock()
.await?
.list_payments(tonic_lnd::lnrpc::ListPaymentsRequest {
include_incomplete: true,
..Default::default()
})
.await?
.into_inner()
.payments
.into_iter()
.find(|p| p.payment_hash == payment.payment_hash.to_hex())
.context("payment not in list")?
.status();
anyhow::ensure!(payment_status == tonic_lnd::lnrpc::payment::PaymentStatus::Succeeded);
}
let ln_recv_time = start_time.elapsed().as_secs_f64() / (iterations as f64);
println!(
"================= RESULTS ==================\n\
AVG REISSUE TIME: {reissue_time:.3}\n\
AVG LN SEND TIME: {ln_send_time:.3}\n\
AVG LN RECV TIME: {ln_recv_time:.3}"
);
Ok(())
}
struct DevFed {
bitcoind: Bitcoind,
cln: Lightningd,
lnd: Lnd,
fed: Federation,
gw_cln: Gatewayd,
gw_lnd: Gatewayd,
}
async fn dev_fed(task_group: &TaskGroup, process_mgr: &ProcessManager) -> Result<DevFed> {
let bitcoind = Bitcoind::new(process_mgr).await?;
let (cln, lnd) = tokio::try_join!(
Lightningd::new(process_mgr, bitcoind.clone()),
Lnd::new(process_mgr, bitcoind.clone()),
)?;
info!("lightning and bitcoind started");
run_dkg(task_group, 4).await?;
info!("dkg done");
open_channel(&bitcoind, &cln, &lnd).await?;
info!("channel open");
let fed = Federation::new(process_mgr, bitcoind.clone(), 0..4).await?;
info!("federation started");
let gw_cln = Gatewayd::new(process_mgr, ClnOrLnd::Cln(cln.clone())).await?;
let gw_lnd = Gatewayd::new(process_mgr, ClnOrLnd::Lnd(lnd.clone())).await?;
info!("gateway started");
tokio::try_join!(gw_cln.connect_fed(&fed), gw_lnd.connect_fed(&fed))?;
fed.await_gateways_registered().await?;
info!("gateways registered");
fed.use_gateway(&gw_cln).await?;
Ok(DevFed {
bitcoind,
cln,
lnd,
fed,
gw_cln,
gw_lnd,
})
}
async fn tmuxinator(process_mgr: &ProcessManager, task_group: &TaskGroup) -> Result<()> {
let ready_file = env::var("FM_READY_FILE")?;
match dev_fed(task_group, process_mgr).await {
Ok(_dev_fed) => {
fs::write(ready_file, "READY").await?;
task_group.make_handle().make_shutdown_rx().await.await?;
Ok(())
}
Err(e) => {
fs::write(ready_file, "ERROR").await?;
Err(e)
}
}
}
use clap::{Parser, Subcommand};
#[derive(Subcommand)]
enum Cmd {
Tmuxinator,
LatencyTests,
}
#[derive(Parser)]
#[command(version)]
struct Args {
#[clap(subcommand)]
command: Cmd,
}
#[tokio::main]
async fn main() -> Result<()> {
fedimint_logging::TracingSetup::default().init()?;
let process_mgr = ProcessManager::new();
let task_group = TaskGroup::new();
task_group.install_kill_handler();
let args = Args::parse();
match args.command {
Cmd::Tmuxinator => tmuxinator(&process_mgr, &task_group).await?,
Cmd::LatencyTests => {
let dev_fed = dev_fed(&task_group, &process_mgr).await?;
latency_tests(dev_fed).await?;
}
}
Ok(())
}