Skip to content

Commit

Permalink
chore: format code to wrap at max width of 120
Browse files Browse the repository at this point in the history
  • Loading branch information
enigbe committed Mar 11, 2024
1 parent 451c3a7 commit 590d834
Show file tree
Hide file tree
Showing 8 changed files with 97 additions and 221 deletions.
1 change: 1 addition & 0 deletions rustfmt.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ edition = "2021"
match_block_trailing_comma = true
newline_style = "Unix"
use_try_shorthand = true
max_width = 120
26 changes: 10 additions & 16 deletions sim-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,13 @@ async fn main() -> anyhow::Result<()> {
);

let sim_path = read_sim_path(opts.data_dir.clone(), opts.sim_file).await?;
let SimParams { nodes, activity } =
serde_json::from_str(&std::fs::read_to_string(sim_path)?)
.map_err(|e| anyhow!("Could not deserialize node connection data or activity description from simulation file (line {}, col {}).", e.line(), e.column()))?;
let SimParams { nodes, activity } = serde_json::from_str(&std::fs::read_to_string(sim_path)?).map_err(|e| {
anyhow!(
"Nodes or activities not parsed from simulation file (line {}, col {}).",
e.line(),
e.column()
)
})?;

let mut clients: HashMap<PublicKey, Arc<Mutex<dyn LightningNode>>> = HashMap::new();
let mut pk_node_map = HashMap::new();
Expand All @@ -55,11 +59,7 @@ async fn main() -> anyhow::Result<()> {

let node_info = node.lock().await.get_info().clone();

log::info!(
"Connected to {} - Node ID: {}.",
node_info.alias,
node_info.pubkey
);
log::info!("Connected to {} - Node ID: {}.", node_info.alias, node_info.pubkey);

if clients.contains_key(&node_info.pubkey) {
anyhow::bail!(LightningError::ValidationError(format!(
Expand Down Expand Up @@ -121,10 +121,7 @@ async fn main() -> anyhow::Result<()> {
.await
.map_err(|e| {
log::debug!("{}", e);
LightningError::ValidationError(format!(
"Destination node unknown or invalid: {}.",
pk,
))
LightningError::ValidationError(format!("Destination node unknown or invalid: {}.", pk,))
})?
}
},
Expand Down Expand Up @@ -196,10 +193,7 @@ async fn select_sim_file(data_dir: PathBuf) -> anyhow::Result<PathBuf> {
.collect::<Vec<_>>();

if sim_files.is_empty() {
anyhow::bail!(
"no simulation files found in {}.",
data_dir.canonicalize()?.display()
);
anyhow::bail!("no simulation files found in {}.", data_dir.canonicalize()?.display());
}

let selection = dialoguer::Select::new()
Expand Down
78 changes: 25 additions & 53 deletions sim-lib/src/cln.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@ use async_trait::async_trait;
use bitcoin::secp256k1::PublicKey;
use bitcoin::Network;
use cln_grpc::pb::{
listpays_pays::ListpaysPaysStatus, node_client::NodeClient, Amount, GetinfoRequest,
KeysendRequest, KeysendResponse, ListchannelsRequest, ListnodesRequest, ListpaysRequest,
ListpaysResponse,
listpays_pays::ListpaysPaysStatus, node_client::NodeClient, Amount, GetinfoRequest, KeysendRequest,
KeysendResponse, ListchannelsRequest, ListnodesRequest, ListpaysRequest, ListpaysResponse,
};
use lightning::ln::features::NodeFeatures;
use lightning::ln::PaymentHash;
Expand All @@ -16,9 +15,7 @@ use tokio::time::{self, Duration};
use tonic::transport::{Certificate, Channel, ClientTlsConfig, Identity};
use triggered::Listener;

use crate::{
serializers, LightningError, LightningNode, NodeId, NodeInfo, PaymentOutcome, PaymentResult,
};
use crate::{serializers, LightningError, LightningNode, NodeId, NodeInfo, PaymentOutcome, PaymentResult};

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ClnConnection {
Expand All @@ -43,48 +40,37 @@ impl ClnNode {
let tls = ClientTlsConfig::new()
.domain_name("cln")
.identity(Identity::from_pem(
reader(&connection.client_cert).await.map_err(|_| {
LightningError::ConnectionError("Cannot loads client certificate".to_string())
})?,
reader(&connection.client_key).await.map_err(|_| {
LightningError::ConnectionError("Cannot loads client key".to_string())
})?,
reader(&connection.client_cert)
.await
.map_err(|_| LightningError::ConnectionError("Cannot loads client certificate".to_string()))?,
reader(&connection.client_key)
.await
.map_err(|_| LightningError::ConnectionError("Cannot loads client key".to_string()))?,
))
.ca_certificate(Certificate::from_pem(
reader(&connection.ca_cert).await.map_err(|_| {
LightningError::ConnectionError("Cannot loads CA certificate".to_string())
})?,
));
.ca_certificate(Certificate::from_pem(reader(&connection.ca_cert).await.map_err(
|_| LightningError::ConnectionError("Cannot loads CA certificate".to_string()),
)?));

let mut client = NodeClient::new(
Channel::from_shared(connection.address.to_string())
.map_err(|err| LightningError::ConnectionError(err.to_string()))?
.tls_config(tls)
.map_err(|_| {
LightningError::ConnectionError("Cannot establish tls connection".to_string())
})?
.map_err(|_| LightningError::ConnectionError("Cannot establish tls connection".to_string()))?
.connect()
.await
.map_err(|_| {
LightningError::ConnectionError("Cannot connect to gRPC server".to_string())
})?,
.map_err(|_| LightningError::ConnectionError("Cannot connect to gRPC server".to_string()))?,
);

let (id, mut alias, our_features) = client
.getinfo(GetinfoRequest {})
.await
.map(|r| {
let inner = r.into_inner();
(
inner.id,
inner.alias.unwrap_or_default(),
inner.our_features,
)
(inner.id, inner.alias.unwrap_or_default(), inner.our_features)
})
.map_err(|err| LightningError::GetInfoError(err.to_string()))?;

let pubkey = PublicKey::from_slice(&id)
.map_err(|err| LightningError::GetInfoError(err.to_string()))?;
let pubkey = PublicKey::from_slice(&id).map_err(|err| LightningError::GetInfoError(err.to_string()))?;
connection.id.validate(&pubkey, &mut alias)?;

let features = if let Some(features) = our_features {
Expand Down Expand Up @@ -148,15 +134,10 @@ impl LightningNode for ClnNode {
.map_err(|err| LightningError::GetInfoError(err.to_string()))?
.into_inner();

Ok(Network::from_core_arg(&info.network)
.map_err(|err| LightningError::ValidationError(err.to_string()))?)
Ok(Network::from_core_arg(&info.network).map_err(|err| LightningError::ValidationError(err.to_string()))?)
}

async fn send_payment(
&mut self,
dest: PublicKey,
amount_msat: u64,
) -> Result<PaymentHash, LightningError> {
async fn send_payment(&mut self, dest: PublicKey, amount_msat: u64) -> Result<PaymentHash, LightningError> {
let KeysendResponse { payment_hash, .. } = self
.client
.key_send(KeysendRequest {
Expand Down Expand Up @@ -186,11 +167,7 @@ impl LightningNode for ClnNode {
Ok(PaymentHash(slice))
}

async fn track_payment(
&mut self,
hash: PaymentHash,
shutdown: Listener,
) -> Result<PaymentResult, LightningError> {
async fn track_payment(&mut self, hash: PaymentHash, shutdown: Listener) -> Result<PaymentResult, LightningError> {
loop {
tokio::select! {
biased;
Expand Down Expand Up @@ -245,19 +222,14 @@ impl LightningNode for ClnNode {
Ok(NodeInfo {
pubkey: *node_id,
alias: node.alias.unwrap_or(String::new()),
features: node
.features
.clone()
.map_or(NodeFeatures::empty(), |mut f| {
// We need to reverse this given it has the CLN wire encoding which is BE
f.reverse();
NodeFeatures::from_le_bytes(f)
}),
features: node.features.clone().map_or(NodeFeatures::empty(), |mut f| {
// We need to reverse this given it has the CLN wire encoding which is BE
f.reverse();
NodeFeatures::from_le_bytes(f)
}),
})
} else {
Err(LightningError::GetNodeInfoError(
"Node not found".to_string(),
))
Err(LightningError::GetNodeInfoError("Node not found".to_string()))
}
}

Expand Down
8 changes: 2 additions & 6 deletions sim-lib/src/defined_activity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,7 @@ impl PaymentGenerator for DefinedPaymentActivity {
self.wait
}

fn payment_amount(
&self,
destination_capacity: Option<u64>,
) -> Result<u64, crate::PaymentGenerationError> {
fn payment_amount(&self, destination_capacity: Option<u64>) -> Result<u64, crate::PaymentGenerationError> {
if destination_capacity.is_some() {
Err(PaymentGenerationError(
"destination amount must not be set for defined activity generator".to_string(),
Expand All @@ -69,8 +66,7 @@ mod tests {
let source = get_random_keypair();
let payment_amt = 50;

let generator =
DefinedPaymentActivity::new(node.clone(), Duration::from_secs(60), payment_amt);
let generator = DefinedPaymentActivity::new(node.clone(), Duration::from_secs(60), payment_amt);

let (dest, dest_capacity) = generator.choose_destination(source.1);
assert_eq!(node.pubkey, dest.pubkey);
Expand Down
Loading

0 comments on commit 590d834

Please sign in to comment.