refactor: clippy suggestions

This commit is contained in:
Greg Heartsfield 2023-07-03 10:31:22 -05:00
parent ddc58a2f1c
commit dad6911807
9 changed files with 35 additions and 38 deletions

View File

@ -204,7 +204,7 @@ impl ClientConn {
} }
} }
match (relay.and_then(|url| host_str(url)), host_str(relay_url)) { match (relay.and_then(host_str), host_str(relay_url)) {
(Some(received_relay), Some(our_relay)) => { (Some(received_relay), Some(our_relay)) => {
if received_relay != our_relay { if received_relay != our_relay {
return Err(Error::AuthFailure); return Err(Error::AuthFailure);

View File

@ -45,8 +45,8 @@ pub const DB_FILE: &str = "nostr.db";
/// Will panic if the pool could not be created. /// Will panic if the pool could not be created.
pub async fn build_repo(settings: &Settings, metrics: NostrMetrics) -> Arc<dyn NostrRepo> { pub async fn build_repo(settings: &Settings, metrics: NostrMetrics) -> Arc<dyn NostrRepo> {
match settings.database.engine.as_str() { match settings.database.engine.as_str() {
"sqlite" => Arc::new(build_sqlite_pool(&settings, metrics).await), "sqlite" => Arc::new(build_sqlite_pool(settings, metrics).await),
"postgres" => Arc::new(build_postgres_pool(&settings, metrics).await), "postgres" => Arc::new(build_postgres_pool(settings, metrics).await),
_ => panic!("Unknown database engine"), _ => panic!("Unknown database engine"),
} }
} }
@ -378,7 +378,7 @@ pub async fn db_writer(
notice_tx notice_tx
.try_send(Notice::blocked( .try_send(Notice::blocked(
event.id, event.id,
&decision.message().unwrap_or_else(|| "".to_string()), &decision.message().unwrap_or_default(),
)) ))
.ok(); .ok();
continue; continue;

View File

@ -472,12 +472,11 @@ mod tests {
let mut event = Event::simple_event(); let mut event = Event::simple_event();
event.tags = vec![vec!["e".to_owned(), "foo".to_owned()]]; event.tags = vec![vec!["e".to_owned(), "foo".to_owned()]];
event.build_index(); event.build_index();
assert_eq!( assert!(
event.generic_tag_val_intersect( event.generic_tag_val_intersect(
'e', 'e',
&HashSet::from(["foo".to_owned(), "bar".to_owned()]) &HashSet::from(["foo".to_owned(), "bar".to_owned()])
), )
true
); );
} }

View File

@ -35,7 +35,7 @@ impl std::convert::From<Nip05Name> for nauthz_grpc::event_request::Nip05Name {
fn from(value: Nip05Name) -> Self { fn from(value: Nip05Name) -> Self {
nauthz_grpc::event_request::Nip05Name { nauthz_grpc::event_request::Nip05Name {
local: value.local.clone(), local: value.local.clone(),
domain: value.domain.clone(), domain: value.domain,
} }
} }
} }
@ -57,7 +57,7 @@ impl EventAuthzService {
eas eas
} }
pub async fn ready_connection(self: &mut Self) { pub async fn ready_connection(&mut self) {
if self.conn.is_none() { if self.conn.is_none() {
let client = AuthorizationClient::connect(self.server_addr.to_string()).await; let client = AuthorizationClient::connect(self.server_addr.to_string()).await;
if let Err(ref msg) = client { if let Err(ref msg) = client {
@ -70,7 +70,7 @@ impl EventAuthzService {
} }
pub async fn admit_event( pub async fn admit_event(
self: &mut Self, &mut self,
event: &Event, event: &Event,
ip: &str, ip: &str,
origin: Option<String>, origin: Option<String>,
@ -99,13 +99,13 @@ impl EventAuthzService {
origin, origin,
user_agent, user_agent,
auth_pubkey, auth_pubkey,
nip05: nip05.map(|x| nauthz_grpc::event_request::Nip05Name::from(x)), nip05: nip05.map(nauthz_grpc::event_request::Nip05Name::from),
}) })
.await?; .await?;
let reply = svr_res.into_inner(); let reply = svr_res.into_inner();
return Ok(Box::new(reply)); Ok(Box::new(reply))
} else { } else {
return Err(Error::AuthzError); Err(Error::AuthzError)
} }
} }
} }

View File

@ -110,7 +110,7 @@ impl PaymentProcessor for LNBitsPaymentProcessor {
expiry: 3600, expiry: 3600,
}; };
let url = Url::parse(&self.settings.pay_to_relay.node_url)?.join(APIPATH)?; let url = Url::parse(&self.settings.pay_to_relay.node_url)?.join(APIPATH)?;
let uri = Uri::from_str(url.as_str().strip_suffix("/").unwrap_or(url.as_str())).unwrap(); let uri = Uri::from_str(url.as_str().strip_suffix('/').unwrap_or(url.as_str())).unwrap();
let req = hyper::Request::builder() let req = hyper::Request::builder()
.method(hyper::Method::POST) .method(hyper::Method::POST)

View File

@ -842,7 +842,8 @@ impl NostrRepo for SqliteRepo {
async fn update_invoice(&self, payment_hash: &str, status: InvoiceStatus) -> Result<String> { async fn update_invoice(&self, payment_hash: &str, status: InvoiceStatus) -> Result<String> {
let mut conn = self.write_pool.get()?; let mut conn = self.write_pool.get()?;
let payment_hash = payment_hash.to_owned(); let payment_hash = payment_hash.to_owned();
let pub_key = tokio::task::spawn_blocking(move || {
tokio::task::spawn_blocking(move || {
let tx = conn.transaction()?; let tx = conn.transaction()?;
let pubkey: String; let pubkey: String;
{ {
@ -884,8 +885,7 @@ impl NostrRepo for SqliteRepo {
let ok: Result<String> = Ok(pubkey); let ok: Result<String> = Ok(pubkey);
ok ok
}) })
.await?; .await?
pub_key
} }
/// Get the most recent invoice for a given pubkey /// Get the most recent invoice for a given pubkey
@ -1080,18 +1080,18 @@ fn query_from_filter(f: &ReqFilter) -> (String, Vec<Box<dyn ToSql>>, Option<Stri
ks.iter().map(std::string::ToString::to_string).collect(); ks.iter().map(std::string::ToString::to_string).collect();
kind_clause = format!("AND kind IN ({})", str_kinds.join(", ")); kind_clause = format!("AND kind IN ({})", str_kinds.join(", "));
} else { } else {
kind_clause = format!(""); kind_clause = String::new();
}; };
if f.since.is_some() { if f.since.is_some() {
since_clause = format!("AND created_at > {}", f.since.unwrap()); since_clause = format!("AND created_at > {}", f.since.unwrap());
} else { } else {
since_clause = format!(""); since_clause = String::new();
}; };
// Query for timestamp // Query for timestamp
if f.until.is_some() { if f.until.is_some() {
until_clause = format!("AND created_at < {}", f.until.unwrap()); until_clause = format!("AND created_at < {}", f.until.unwrap());
} else { } else {
until_clause = format!(""); until_clause = String::new();
}; };
let tag_clause = format!( let tag_clause = format!(

View File

@ -1125,8 +1125,8 @@ async fn nostr_server(
let unspec = "<unspecified>".to_string(); let unspec = "<unspecified>".to_string();
info!("new client connection (cid: {}, ip: {:?})", cid, conn.ip()); info!("new client connection (cid: {}, ip: {:?})", cid, conn.ip());
let origin = client_info.origin.as_ref().unwrap_or_else(|| &unspec); let origin = client_info.origin.as_ref().unwrap_or(&unspec);
let user_agent = client_info.user_agent.as_ref().unwrap_or_else(|| &unspec); let user_agent = client_info.user_agent.as_ref().unwrap_or(&unspec);
info!( info!(
"cid: {}, origin: {:?}, user-agent: {:?}", "cid: {}, origin: {:?}, user-agent: {:?}",
cid, origin, user_agent cid, origin, user_agent
@ -1175,15 +1175,13 @@ async fn nostr_server(
if query_result.event == "EOSE" { if query_result.event == "EOSE" {
let send_str = format!("[\"EOSE\",\"{subesc}\"]"); let send_str = format!("[\"EOSE\",\"{subesc}\"]");
ws_stream.send(Message::Text(send_str)).await.ok(); ws_stream.send(Message::Text(send_str)).await.ok();
} else { } else if allowed_to_send(&query_result.event, &conn, &settings) {
if allowed_to_send(&query_result.event, &conn, &settings) {
metrics.sent_events.with_label_values(&["db"]).inc(); metrics.sent_events.with_label_values(&["db"]).inc();
client_received_event_count += 1; client_received_event_count += 1;
// send a result // send a result
let send_str = format!("[\"EVENT\",\"{}\",{}]", subesc, &query_result.event); let send_str = format!("[\"EVENT\",\"{}\",{}]", subesc, &query_result.event);
ws_stream.send(Message::Text(send_str)).await.ok(); ws_stream.send(Message::Text(send_str)).await.ok();
} }
}
}, },
// TODO: consider logging the LaggedRecv error // TODO: consider logging the LaggedRecv error
Ok(global_event) = bcast_rx.recv() => { Ok(global_event) = bcast_rx.recv() => {
@ -1278,7 +1276,7 @@ async fn nostr_server(
// check if the event is too far in the future. // check if the event is too far in the future.
} else if e.is_valid_timestamp(settings.options.reject_future_seconds) { } else if e.is_valid_timestamp(settings.options.reject_future_seconds) {
// Write this to the database. // Write this to the database.
let auth_pubkey = conn.auth_pubkey().and_then(|pubkey| hex::decode(&pubkey).ok()); let auth_pubkey = conn.auth_pubkey().and_then(|pubkey| hex::decode(pubkey).ok());
let submit_event = SubmittedEvent { let submit_event = SubmittedEvent {
event: e.clone(), event: e.clone(),
notice_tx: notice_tx.clone(), notice_tx: notice_tx.clone(),
@ -1307,7 +1305,7 @@ async fn nostr_server(
error!("AUTH command received, but relay_url is not set in the config file (cid: {})", cid); error!("AUTH command received, but relay_url is not set in the config file (cid: {})", cid);
}, },
Some(relay) => { Some(relay) => {
match conn.authenticate(&event, &relay) { match conn.authenticate(&event, relay) {
Ok(_) => { Ok(_) => {
let pubkey = match conn.auth_pubkey() { let pubkey = match conn.auth_pubkey() {
Some(k) => k.chars().take(8).collect(), Some(k) => k.chars().take(8).collect(),

View File

@ -50,15 +50,15 @@ mod tests {
#[test] #[test]
fn lower_hex() { fn lower_hex() {
let hexstr = "abcd0123"; let hexstr = "abcd0123";
assert_eq!(is_lower_hex(hexstr), true); assert!(is_lower_hex(hexstr));
} }
#[test] #[test]
fn nip19() { fn nip19() {
let hexkey = "3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d"; let hexkey = "3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d";
let nip19key = "npub180cvv07tjdrrgpa0j7j7tmnyl2yr6yr7l8j4s3evf6u64th6gkwsyjh6w6"; let nip19key = "npub180cvv07tjdrrgpa0j7j7tmnyl2yr6yr7l8j4s3evf6u64th6gkwsyjh6w6";
assert_eq!(is_nip19(hexkey), false); assert!(!is_nip19(hexkey));
assert_eq!(is_nip19(nip19key), true); assert!(is_nip19(nip19key));
} }
#[test] #[test]

View File

@ -334,9 +334,9 @@ mod tests {
id: "0".to_owned(), id: "0".to_owned(),
pubkey: public_key.to_hex(), pubkey: public_key.to_hex(),
delegated_by: None, delegated_by: None,
created_at: created_at, created_at,
kind: kind, kind,
tags: tags, tags,
content: "".to_owned(), content: "".to_owned(),
sig: "0".to_owned(), sig: "0".to_owned(),
tagidx: None, tagidx: None,