Skip to content

Commit

Permalink
fix all clippy warnings
Browse files Browse the repository at this point in the history
Signed-off-by: Nitesh Balusu <[email protected]>
  • Loading branch information
niteshbalusu11 committed Aug 8, 2024
1 parent 9bc0972 commit b14cebb
Show file tree
Hide file tree
Showing 11 changed files with 55 additions and 85 deletions.
6 changes: 3 additions & 3 deletions src/credentials/get_cert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@ pub fn get_cert() -> String {
panic!("ExpectedEitherTlsCertPathOrTlsCertHexToAuthenticateToLnd");
}

if !cert_path.is_err() && !cert_path.as_ref().unwrap().is_empty() {
if cert_path.is_ok() && !cert_path.as_ref().unwrap().is_empty() {
let cert_bytes = fs::read(cert_path.unwrap()).expect("FailedToReadTlsCertFile");

return hex::encode(cert_bytes);
hex::encode(cert_bytes)
} else {
return cert_hex.unwrap();
cert_hex.unwrap()
}
}
6 changes: 2 additions & 4 deletions src/credentials/get_lnd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,9 @@ pub async fn get_lnd() -> LndClient {
let macaroon = get_macaroon();
let socket = get_socket();

let client = lnd_grpc_rust::connect(cert, macaroon, socket)
lnd_grpc_rust::connect(cert, macaroon, socket)
.await
.expect("FailedToAuthenticateToLnd");

return client;
.expect("FailedToAuthenticateToLnd")
}

pub async fn test_invoice(mut client: LndClient) -> Result<(), anyhow::Error> {
Expand Down
6 changes: 3 additions & 3 deletions src/credentials/get_macaroon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@ pub fn get_macaroon() -> String {
panic!("ExpectedEitherMacaroonPathOrMacaroonHexToAuthenticateToLnd");
}

if !macaroon_path.is_err() && !macaroon_path.as_ref().unwrap().is_empty() {
if macaroon_path.is_ok() && !macaroon_path.as_ref().unwrap().is_empty() {
let mac_bytes = fs::read(macaroon_path.unwrap()).expect("FailedToReadMacaroonFile");

return hex::encode(mac_bytes);
hex::encode(mac_bytes)
} else {
return macaroon_hex.unwrap();
macaroon_hex.unwrap()
}
}
4 changes: 1 addition & 3 deletions src/credentials/get_socket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,5 @@ use crate::server::constants::EnvVariables;
pub fn get_socket() -> String {
dotenv().ok();

let socket = std::env::var(EnvVariables::SOCKET).expect("ExpectedSocketToAuthenticateToLnd");

return socket;
std::env::var(EnvVariables::SOCKET).expect("ExpectedSocketToAuthenticateToLnd")
}
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ async fn main() -> Result<(), anyhow::Error> {

nip05_broadcast(domain, username).await;

start_server().await;
start_server().await?;

Ok(())
}
1 change: 1 addition & 0 deletions src/server/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ pub const CONSTANTS: Constants = Constants {
min_sendamount: 1000,
};

#[allow(clippy::upper_case_acronyms)]
#[allow(non_camel_case_types)]
pub enum EnvVariables {
USERNAME,
Expand Down
24 changes: 11 additions & 13 deletions src/server/handle_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,17 @@ use super::{

pub async fn handle_request(req: Request<Body>) -> Result<Response<Body>, hyper::Error> {
match (req.method(), req.uri().path()) {
(&hyper::Method::GET, "/") => {
return handle_default_path();
}
(&hyper::Method::GET, "/") => handle_default_path(),

(&hyper::Method::GET, path) if path.starts_with("/.well-known/lnurlp/") => {
return handle_invoice_path(path, req.uri()).await
handle_invoice_path(path, req.uri()).await
}

(&hyper::Method::GET, path) if path.starts_with("/.well-known/nostr.json") => {
return handle_nip05_path(req.uri()).await
handle_nip05_path(req.uri()).await
}
// Return 404 Not Found for any other requests
_ => return handle_unknown_path(),
_ => handle_unknown_path(),
}
}

Expand Down Expand Up @@ -65,7 +63,7 @@ fn handle_default_path() -> Result<Response<Body>, hyper::Error> {
let response_body_string = serde_json::to_string(&response_body)
.expect("Failed to serialize response body to JSON");

return handle_ok_request(response_body_string);
handle_ok_request(response_body_string)
}
Err(_) => handle_bad_request("Failed To Encode Lnurl"),
}
Expand All @@ -86,7 +84,7 @@ fn handle_unknown_path() -> Result<Response<Body>, hyper::Error> {
let response_body_string =
serde_json::to_string(&response_body).expect("Failed to serialize response body to JSON");

return handle_ok_request(response_body_string);
handle_ok_request(response_body_string)
}

#[derive(Serialize, Deserialize)]
Expand All @@ -106,7 +104,7 @@ struct SuccessAction {
}

async fn handle_invoice_path(path: &str, uri: &Uri) -> Result<Response<Body>, hyper::Error> {
let username = path.rsplitn(2, '/').next();
let username = path.rsplit('/').next();
let response_body_string = handle_response_body();

match username {
Expand Down Expand Up @@ -165,9 +163,9 @@ async fn handle_invoice_path(path: &str, uri: &Uri) -> Result<Response<Body>, hy

return handle_ok_request(success_response_body_string);
}
return handle_ok_request(response_body_string);
handle_ok_request(response_body_string)
}
_ => return handle_bad_request("Username Not Found"),
_ => handle_bad_request("Username Not Found"),
}
}

Expand All @@ -177,7 +175,7 @@ async fn handle_nip05_path(uri: &Uri) -> Result<Response<Body>, hyper::Error> {
Err(_) => return handle_bad_request("Failed To Get Nostr Keys"),
};

let relays = CONSTANTS.relays.clone();
let relays = CONSTANTS.relays;
let username = std::env::var(EnvVariables::USERNAME).unwrap();

let default_response_body = json!({
Expand Down Expand Up @@ -230,5 +228,5 @@ async fn handle_nip05_path(uri: &Uri) -> Result<Response<Body>, hyper::Error> {

return handle_ok_request(response_body_string);
}
return handle_ok_request(default_response_body_string);
handle_ok_request(default_response_body_string)
}
45 changes: 19 additions & 26 deletions src/server/parsing_functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ pub fn parse_amount_query(key: Option<(String, String)>) -> Result<i64, String>

match amount {
Ok(a) => {
if a < CONSTANTS.min_sendamount || a > CONSTANTS.max_sendamount {
if !(CONSTANTS.min_sendamount..=CONSTANTS.max_sendamount).contains(&a) {
return Err("AmountOutOfRange".to_string());
}

Expand All @@ -76,7 +76,7 @@ pub fn parse_comment_query(key: Option<(String, String)>) -> Result<String, Stri
return Err("CommentCannotBeBlankOrGreaterThan50Characters".to_string());
}

return Ok(comment);
Ok(comment)
}

None => Ok("".to_string()),
Expand All @@ -85,9 +85,7 @@ pub fn parse_comment_query(key: Option<(String, String)>) -> Result<String, Stri

pub fn parse_name_query(key: Option<(String, String)>) -> Result<String, String> {
match key {
Some((_, comment)) => {
return Ok(comment);
}
Some((_, comment)) => Ok(comment),

None => Err("".to_string()),
}
Expand Down Expand Up @@ -122,10 +120,8 @@ pub fn parse_nostr_query(key: Option<(String, String)>) -> Result<SignedEvent, S
return Err("MissingP-TagsInZapRequest".to_string());
}

if ptags.is_some() {
if ptags.unwrap().len() >= 2 {
return Err("MultipleP-TagsArePresentInTheZapRequest".to_string());
}
if ptags.is_some() && ptags.unwrap().len() >= 2 {
return Err("MultipleP-TagsArePresentInTheZapRequest".to_string());
}

let etags = get_tags(&tags, "e");
Expand All @@ -142,7 +138,7 @@ pub fn parse_nostr_query(key: Option<(String, String)>) -> Result<SignedEvent, S

let event = UnsignedEvent {
content: p.content.clone(),
created_at: p.created_at as i64,
created_at: p.created_at,
kind: p.kind,
tags: p.tags.clone(),
pubkey: p.pubkey.clone(),
Expand All @@ -161,25 +157,25 @@ pub fn parse_nostr_query(key: Option<(String, String)>) -> Result<SignedEvent, S
return Err("FailedToGetNostrKeys".to_string());
}

return Ok(p);
Ok(p)
}

Err(_) => return Err("FailedToParseNostrQuery".to_string()),
};
Err(_) => Err("FailedToParseNostrQuery".to_string()),
}
}

_ => Err("".to_string()),
}
}

pub fn get_tags(tags: &Vec<Vec<String>>, key: &str) -> Option<Vec<String>> {
pub fn get_tags(tags: &[Vec<String>], key: &str) -> Option<Vec<String>> {
let mut values = Vec::new();

for tag in tags.iter() {
if tag[0] == key {
if key == "relays" {
for i in 1..tag.len() {
values.push(tag[i].clone());
for value in tag.iter().skip(1) {
values.push(value.clone());
}
} else {
values.push(tag[1].clone());
Expand Down Expand Up @@ -241,10 +237,7 @@ pub fn handle_response_body() -> String {
response_body["nostrPubkey"] = serde_json::Value::String(pubkey);
}

let response_body_string =
serde_json::to_string(&response_body).expect("Failed to serialize response body to JSON");

return response_body_string;
serde_json::to_string(&response_body).expect("Failed to serialize response body to JSON")
}

pub fn get_digest(nostr: Option<&SignedEvent>) -> Vec<u8> {
Expand All @@ -260,10 +253,10 @@ pub fn get_digest(nostr: Option<&SignedEvent>) -> Vec<u8> {
])
.expect("Failed to serialize metadata");

let metadata = if nostr.is_none() {
default_metadata
let metadata = if let Some(nostr_event) = nostr {
serde_json::to_string(&Some(nostr_event)).unwrap_or(default_metadata)
} else {
serde_json::to_string(&Some(nostr.unwrap())).unwrap_or(default_metadata)
default_metadata
};

hasher.update(metadata.as_bytes());
Expand All @@ -273,7 +266,7 @@ pub fn get_digest(nostr: Option<&SignedEvent>) -> Vec<u8> {

pub fn convert_key(key: &str) -> String {
match ConvertKey::to_hex(key) {
Ok(key) => return key,
Err(_) => return key.to_string(),
};
Ok(key) => key,
Err(_) => key.to_string(),
}
}
11 changes: 3 additions & 8 deletions src/server/publish_to_relay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,7 @@ pub fn publish_zap_to_relays(
comment.to_string()
};

let mut tags = Vec::new();
tags.push(ptags);
tags.push(etags);
tags.push(bolt11);
tags.push(payment_secret);
tags.push(description);
let tags = vec![ptags, etags, bolt11, payment_secret, description];

let event: UnsignedEvent = UnsignedEvent {
pubkey: pubkey.clone(),
Expand Down Expand Up @@ -90,7 +85,7 @@ pub async fn publish(relays: Vec<String>, publish_message: String) {

for relay in relays {
let (host, port) = match relay.split_once("://") {
Some((_, addr)) => match addr.split_once(":") {
Some((_, addr)) => match addr.split_once(':') {
Some((host, port)) => (host, port),
None => (addr, "443"),
},
Expand All @@ -105,7 +100,7 @@ pub async fn publish(relays: Vec<String>, publish_message: String) {
let results = join_all(futures).await;

// Handle any errors that occurred
for (_index, _result) in results.into_iter().enumerate() {}
for _result in results.into_iter() {}
}

async fn send_message(uri: String, message: String) -> Result<(), ()> {
Expand Down
9 changes: 2 additions & 7 deletions src/server/start_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::net::Ipv4Addr;
use crate::server::constants::EnvVariables;
use crate::server::handle_request::handle_request;

pub async fn start_server() {
pub async fn start_server() -> Result<(), hyper::Error> {
let default_host = "127.0.0.1".parse::<Ipv4Addr>().unwrap();
let default_port = 3000;

Expand Down Expand Up @@ -46,10 +46,5 @@ pub async fn start_server() {
let server = Server::bind(&addr).serve(make_svc);
println!("Listening on http://{}", addr);

let res = server.await;

match res {
Err(e) => panic!("FailedToStartHttpServer {}", e),
_ => return,
}
server.await
}
26 changes: 9 additions & 17 deletions src/server/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ pub fn get_identifiers() -> (String, String) {
let domain = std::env::var(EnvVariables::DOMAIN).unwrap();
let username = std::env::var(EnvVariables::USERNAME).unwrap();

return (domain, username);
(domain, username)
}

pub fn bech32_encode(prefix: String, data: String) -> Result<String, bech32::Error> {
Expand Down Expand Up @@ -118,12 +118,7 @@ pub async fn create_invoice(
invoice_result.payment_request
}

async fn watch_invoice(
zap_request: SignedEvent,
mut lnd: LndClient,
r_hash: &Vec<u8>,
comment: &str,
) {
async fn watch_invoice(zap_request: SignedEvent, mut lnd: LndClient, r_hash: &[u8], comment: &str) {
let mut invoice_subscription = lnd
.invoices()
.subscribe_single_invoice(SubscribeSingleInvoiceRequest {
Expand Down Expand Up @@ -173,7 +168,7 @@ pub async fn nip05_broadcast(domain: String, username: String) {

let event = UnsignedEvent {
content: content.clone(),
created_at: timestamp.clone() as i64,
created_at: timestamp as i64,
kind: 0,
tags: [].to_vec(),
pubkey: pubkey.clone(),
Expand Down Expand Up @@ -208,24 +203,21 @@ pub async fn nip05_broadcast(domain: String, username: String) {
}

pub fn get_relays(relays: Option<Vec<String>>) -> Vec<String> {
let arg_relays = relays.unwrap_or(vec![]);
let arg_relays = relays.unwrap_or_default();

let env_relays = std::env::var(EnvVariables::RELAYS);
let mut env_relays_vec: Vec<String> = vec![];

match env_relays {
Ok(ref r) => {
env_relays_vec = r.split(',').map(|s| s.to_string()).collect();
}
Err(_) => {}
};
if let Ok(ref r) = env_relays {
env_relays_vec = r.split(',').map(|s| s.to_string()).collect();
}

let default_relays: Vec<String> = CONSTANTS.relays.iter().map(|s| s.to_string()).collect();

// Create a HashSet from both vectors to remove duplicates.
let mut combined_relays: HashSet<String> = env_relays_vec.into_iter().collect();
combined_relays.extend(default_relays.into_iter());
combined_relays.extend(arg_relays.into_iter());
combined_relays.extend(default_relays);
combined_relays.extend(arg_relays);

let unique_relays: Vec<String> = combined_relays.into_iter().collect();

Expand Down

0 comments on commit b14cebb

Please sign in to comment.