Skip to content

Commit

Permalink
cargo fmt + cargo clippy
Browse files Browse the repository at this point in the history
  • Loading branch information
evd0kim committed Feb 6, 2023
1 parent 3ab203f commit 5cf4b3d
Show file tree
Hide file tree
Showing 8 changed files with 102 additions and 51 deletions.
2 changes: 1 addition & 1 deletion cln-btc-test/src/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ fn handle_defaults<'a, 'b>(
if args[args_i] == serde_json::Value::Null {
if first_non_null_optional_idx.is_some() {
if defaults[defaults_i] == serde_json::Value::Null {
panic!("Missing `default` for argument idx {}", args_i);
panic!("Missing `default` for argument idx {args_i}");
}
args[args_i] = defaults[defaults_i].clone();
}
Expand Down
22 changes: 11 additions & 11 deletions cln-btc-test/src/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ pub async fn setup_btc_node_ready(port: u16, rpc_port: u16) -> (Child, Client, T
&rpc_url,
Auth::UserPass("regtest".to_owned(), "regtest".to_owned()),
)
.expect("Node client");
.expect("Node client");
wait_for_btc_node(&client).await;
client
.create_wallet("default", None, None, None, None)
Expand Down Expand Up @@ -78,9 +78,9 @@ pub async fn generate_to_address(client: &Client, address: Address) {
}

pub async fn run_btc_test<F, Fut>(test_body: F)
where
F: FnOnce(Client) -> Fut,
Fut: Future<Output = ()>,
where
F: FnOnce(Client) -> Fut,
Fut: Future<Output = ()>,
{
let _ = env_logger::builder().is_test(true).try_init();
let node_port = random_free_tcp_port().expect("available port");
Expand All @@ -96,9 +96,9 @@ pub async fn run_btc_test<F, Fut>(test_body: F)
}

pub async fn run_two_nodes_test<F, Fut>(test_body: F)
where
F: FnOnce(Client, Client) -> Fut,
Fut: Future<Output = ()>,
where
F: FnOnce(Client, Client) -> Fut,
Fut: Future<Output = ()>,
{
let _ = env_logger::builder().is_test(true).try_init();

Expand Down Expand Up @@ -127,9 +127,9 @@ pub async fn run_two_nodes_test<F, Fut>(test_body: F)
// user's balance from an external wallet.
// It also starts instance of hexstody-btc API.
pub async fn run_regtest<F, Fut>(body: F)
where
F: FnOnce((u16, Client), (u16, Client)) -> Fut,
Fut: Future<Output = ()>,
where
F: FnOnce((u16, Client), (u16, Client)) -> Fut,
Fut: Future<Output = ()>,
{
// Start 1st BTC node
let node_1_port = 9803;
Expand Down Expand Up @@ -167,7 +167,7 @@ pub async fn run_regtest<F, Fut>(body: F)
(node_2_rpc_port, client_2),
//(api_url, api_client),
)
.await;
.await;
teardown_btc_node(node_1_handle);
teardown_btc_node(node_2_handle);
}
20 changes: 11 additions & 9 deletions cln-test/src/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ use std::process::{Child, Command, Stdio};
use std::time::Duration;
use tempdir::TempDir;

use clightningrpc::LightningRPC;
use bitcoin::Address;
use clightningrpc::LightningRPC;

use cln_btc_test::runner::*;

Expand Down Expand Up @@ -159,8 +159,12 @@ async fn setup_cln_peernode_ready(
(node_handle, client, temp_dir)
}

pub async fn mine_and_sync(btc: &Client, block_num: u64, address: &Address, ln_nodes: Vec<&LightningRPC>) -> u64
{
pub async fn mine_and_sync(
btc: &Client,
block_num: u64,
address: &Address,
ln_nodes: Vec<&LightningRPC>,
) -> u64 {
let _r = btc
.generate_to_address(block_num, address)
.expect("New blocks");
Expand All @@ -182,24 +186,22 @@ pub async fn mine_and_sync(btc: &Client, block_num: u64, address: &Address, ln_n
chain_info.blocks
}

pub async fn wait_for_htlc(cln: &LightningRPC) -> u64
{
pub async fn wait_for_htlc(cln: &LightningRPC) -> u64 {
// Ensures all HTLC settled
// scids can be a list of strings. If unset wait on all channels.
let peers = cln.listpeers(None, None).expect("All peers of the node");
let mut msec = 0;
for p in peers.peers {
for c in p.channels {
if c.htlcs.len() > 0 {
if !c.htlcs.is_empty() {
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
msec = msec + 100;
msec += 100;
}
}
};
}
msec
}


pub async fn run_cln_test<F, Fut>(test_body: F)
where
F: FnOnce(Client, LightningRPC, LightningRPC) -> Fut,
Expand Down
2 changes: 1 addition & 1 deletion plugin/src/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ impl<'a, T: 'a + Clone> Plugin<T> {
if let Err(json_res) = notification.call(self, params) {
self.log(
LogLevel::Debug,
format!("Notification end with and error: {}", json_res).as_str(),
format!("Notification end with and error: {json_res}").as_str(),
);
}
}
Expand Down
13 changes: 10 additions & 3 deletions rpc/src/lightningrpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,14 @@ impl LightningRPC {
source: Option<&str>,
destination: Option<&str>,
) -> Result<responses::ListChannels, Error> {
self.call("listchannels", requests::ListChannels { short_channel_id, source, destination })
self.call(
"listchannels",
requests::ListChannels {
short_channel_id,
source,
destination,
},
)
}

/// List available commands, or give verbose help on one command.
Expand Down Expand Up @@ -184,7 +191,7 @@ impl LightningRPC {
requests::CreateInvoice {
invstring,
label,
preimage
preimage,
},
)
}
Expand Down Expand Up @@ -435,7 +442,7 @@ impl LightningRPC {
destination,
satoshi,
feerate,
minconf
minconf,
},
)
}
Expand Down
2 changes: 1 addition & 1 deletion rpc/src/responses.rs
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ pub struct CreateinvoiceResponse {
pub bolt12: Option<String>,
pub payment_hash: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub amount_msat: Option<MSat>,
pub amount_msat: Option<MSat>,
pub status: String,
pub description: String,
pub expires_at: u64,
Expand Down
3 changes: 1 addition & 2 deletions rpc/tests/btc_regtest.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use bitcoincore_rpc::RpcApi;
use cln_btc_test::runner::run_btc_test;


// Check that we have node and API operational
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn basic_test() {
Expand All @@ -10,5 +9,5 @@ async fn basic_test() {
let info = btc.get_blockchain_info().expect("blockchain info");
assert_eq!(info.chain, "regtest");
})
.await;
.await;
}
89 changes: 66 additions & 23 deletions rpc/tests/cln_regtest.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use bitcoincore_rpc::bitcoin::Address;
use bitcoincore_rpc::RpcApi;
use clightningrpc::responses::NetworkAddress::Ipv4;
use std::str::FromStr;
use clightningrpc::lightningrpc::PayOptions;
use clightningrpc::requests::AmountOrAll;
use clightningrpc::responses::NetworkAddress::Ipv4;
use p256::elliptic_curve::weierstrass::add;
use std::str::FromStr;

use cln_btc_test::runner::*;
use cln_test::runner::*;
Expand All @@ -13,7 +13,6 @@ use cln_test::runner::*;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn basic_test() {
run_cln_test(|btc, cln_back, cln_peer| async move {

println!("Getting info from Bitcoind");
let info = btc.get_blockchain_info().expect("blockchain info");
println!("Blockchain tip {}", info.blocks);
Expand All @@ -37,7 +36,10 @@ async fn basic_test() {
let info = btc.get_blockchain_info().expect("BTC blockchain info");
let info_back = cln_back.getinfo().expect("CLN blockchain info");
let info_peer = cln_peer.getinfo().expect("CLN blockchain info");
println!("Network synced: Core tip {}, CLN Back height {}, CLN Peer height {} ", info.blocks, info_back.blockheight, info_peer.blockheight);
println!(
"Network synced: Core tip {}, CLN Back height {}, CLN Peer height {} ",
info.blocks, info_back.blockheight, info_peer.blockheight
);

let mut uri = format!("{}", info_peer.id);
for addr in info_peer.binding {
Expand All @@ -51,23 +53,35 @@ async fn basic_test() {
}

println!("Opening channel with {}", uri);
let connect = cln_back.connect(uri.as_str(), None).expect("Connecting to peer node");
let connect = cln_back
.connect(uri.as_str(), None)
.expect("Connecting to peer node");

println!("Connected {}, features {}", connect.id, connect.features);

let funding = cln_back.fundchannel(info_peer.id.as_str(), AmountOrAll::All, Some(5)).expect("Channel funding");
let funding = cln_back
.fundchannel(info_peer.id.as_str(), AmountOrAll::All, Some(5))
.expect("Channel funding");
println!("{} - {}", funding.txid, funding.channel_id);

let _h = mine_and_sync(&btc, 101, &addr, vec![&cln_back, &cln_peer]).await;

let info_back = cln_back.getinfo().expect("CLN blockchain info");
let info_peer = cln_peer.getinfo().expect("CLN blockchain info");
println!("CLN Back peers {}, CLN Peer peers {} ", info_back.num_peers, info_peer.num_peers);
println!("CLN Back channels active {}, CLN Peer channels active {} ", info_back.num_active_channels, info_peer.num_active_channels);
println!(
"CLN Back peers {}, CLN Peer peers {} ",
info_back.num_peers, info_peer.num_peers
);
println!(
"CLN Back channels active {}, CLN Peer channels active {} ",
info_back.num_active_channels, info_peer.num_active_channels
);

let a = cln_peer.newaddr(None).expect("address wasn't provided");
let addr_str = a.bech32.unwrap();
let withdraw = cln_back.withdraw(addr_str.as_str(), AmountOrAll::Amount(10000), None, None).expect("Withdraw");
let withdraw = cln_back
.withdraw(addr_str.as_str(), AmountOrAll::Amount(10000), None, None)
.expect("Withdraw");
println!("Withdraw to {} Passed: {}", addr_str, withdraw.txid);

let fees = cln_back.feerates("perkw").expect("Network fees");
Expand All @@ -79,7 +93,9 @@ async fn basic_test() {
// let node update graph
tokio::time::sleep(std::time::Duration::from_millis(1000)).await;

let chans = cln_back.listchannels(None, None, None).expect("Node channels");
let chans = cln_back
.listchannels(None, None, None)
.expect("Node channels");
println!("List Channels Passed: {} channels", chans.channels.len());

let funds = cln_back.listfunds().expect("Node funds");
Expand All @@ -90,43 +106,70 @@ async fn basic_test() {
let preimage = "0000000000000000000000000000000000000000000000000000000000000000";
let hash = "66687aadf862bd776c8fc18b8e9f8e20089714856ee233b3902a591d0d5f2925";

let invoice = cln_peer.invoice(Some(10000000),
format!("payment - {}", n).as_str(),
"test",
Some(preimage),
None).expect("Failed to get invoice");
let invoice = cln_peer
.invoice(
Some(10000000),
format!("payment - {}", n).as_str(),
"test",
Some(preimage),
None,
)
.expect("Failed to get invoice");
println!("{:?}", invoice);

let invoices = cln_peer.listinvoices(None, None, None, None).expect("Failed to get invoices");
let invoices = cln_peer
.listinvoices(None, None, None, None)
.expect("Failed to get invoices");
println!("{:?}", invoices);

let _i = btc.get_blockchain_info().expect("BTC blockchain info");
//let _h = mine_and_sync(&btc, 1, &addr, vec![&cln_back, &cln_peer]).await;

let decoded = cln_back.decodepay(invoice.bolt11.as_str(), None).expect("Decoded invoice");
let decoded = cln_back
.decodepay(invoice.bolt11.as_str(), None)
.expect("Decoded invoice");
println!("Decode invoice passed {}", n);

let route = cln_back.getroute(info_peer.id.as_str(), decoded.amount_msat.unwrap().0, 0.0, None, None, None, None).expect("Route to the peer");
let route = cln_back
.getroute(
info_peer.id.as_str(),
decoded.amount_msat.unwrap().0,
0.0,
None,
None,
None,
None,
)
.expect("Route to the peer");
println!("Get route passed, {} hops", route.route.len());

//let pay = cln_back.pay(invoice.bolt11.as_str(), Default::default()).expect("Payment doesn't go");
//wait_for_htlc(&cln_back).await;
//println!("{:?}", pay);
assert_eq!(decoded.payment_hash.as_str(), hash);
let sendpay = cln_back.sendpay(route.route, decoded.payment_hash.as_str(), None, Some(decoded.amount_msat.unwrap().0)).expect("Payment doesn't go");
let sendpay = cln_back
.sendpay(
route.route,
decoded.payment_hash.as_str(),
None,
Some(decoded.amount_msat.unwrap().0),
)
.expect("Payment doesn't go");
println!("Sendpay {} passed {:?}", n, sendpay);
let wait = cln_back.waitsendpay(decoded.payment_hash.as_str(), 120).expect("Waiting for payment");
let wait = cln_back
.waitsendpay(decoded.payment_hash.as_str(), 120)
.expect("Waiting for payment");
println!("Wait sendpay passed {:?}", wait);

let _i = btc.get_blockchain_info().expect("BTC blockchain info");
//let _h = mine_and_sync(&btc, 1, &addr, vec![&cln_back, &cln_peer]).await;
tokio::time::sleep(std::time::Duration::from_millis(10000)).await;
};
}

let listpays = cln_back.listsendpays(None, None).expect("Sent payments");
for p in listpays.payments {
println!("Payment {:?}", p);
};
}

/*
let logs = cln_back.getlog(None).expect("Expected logs");
Expand All @@ -141,5 +184,5 @@ async fn basic_test() {

tokio::time::sleep(std::time::Duration::from_millis(1000)).await;
})
.await;
.await;
}

0 comments on commit 5cf4b3d

Please sign in to comment.