Skip to content
This repository has been archived by the owner on Nov 6, 2020. It is now read-only.

fix(rpc): fix a bunch of clippy lints #10493

Merged
merged 4 commits into from
Mar 22, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions parity/rpc_apis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ impl FullDependencies {
handler.extend_with(DebugClient::new(self.client.clone()).to_delegate());
}
Api::Web3 => {
handler.extend_with(Web3Client::new().to_delegate());
handler.extend_with(Web3Client::default().to_delegate());
}
Api::Net => {
handler.extend_with(NetClient::new(&self.sync).to_delegate());
Expand Down Expand Up @@ -529,7 +529,7 @@ impl<C: LightChainClient + 'static> LightDependencies<C> {
warn!(target: "rpc", "Debug API is not available in light client mode.")
}
Api::Web3 => {
handler.extend_with(Web3Client::new().to_delegate());
handler.extend_with(Web3Client::default().to_delegate());
}
Api::Net => {
handler.extend_with(light::NetClient::new(self.sync.clone()).to_delegate());
Expand Down
12 changes: 6 additions & 6 deletions rpc/src/authcodes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ const TIME_THRESHOLD: u64 = 7;
/// minimal length of hash
const TOKEN_LENGTH: usize = 16;
/// Separator between fields in serialized tokens file.
const SEPARATOR: &'static str = ";";
const SEPARATOR: &str = ";";
/// Number of seconds to keep unused tokens.
const UNUSED_TOKEN_TIMEOUT: u64 = 3600 * 24; // a day

Expand Down Expand Up @@ -115,7 +115,7 @@ impl AuthCodes<DefaultTimeProvider> {
})
.collect();
Ok(AuthCodes {
codes: codes,
codes,
now: time_provider,
})
}
Expand All @@ -128,7 +128,7 @@ impl<T: TimeProvider> AuthCodes<T> {
pub fn to_file(&self, file: &Path) -> io::Result<()> {
let mut file = fs::File::create(file)?;
let content = self.codes.iter().map(|code| {
let mut data = vec![code.code.clone(), encode_time(code.created_at.clone())];
let mut data = vec![code.code.clone(), encode_time(code.created_at)];
if let Some(used_at) = code.last_used_at {
data.push(encode_time(used_at));
}
Expand All @@ -141,11 +141,11 @@ impl<T: TimeProvider> AuthCodes<T> {
pub fn new(codes: Vec<String>, now: T) -> Self {
AuthCodes {
codes: codes.into_iter().map(|code| Code {
code: code,
code,
created_at: time::Duration::from_secs(now.now()),
last_used_at: None,
}).collect(),
now: now,
now,
}
}

Expand Down Expand Up @@ -183,7 +183,7 @@ impl<T: TimeProvider> AuthCodes<T> {
.join("-");
trace!(target: "signer", "New authentication token generated.");
self.codes.push(Code {
code: code,
code,
created_at: time::Duration::from_secs(self.now.now()),
last_used_at: None,
});
Expand Down
2 changes: 1 addition & 1 deletion rpc/src/http_common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ impl<M, T> http::MetaExtractor<M> for MetaExtractor<T> where
{
fn read_metadata(&self, req: &hyper::Request<hyper::Body>) -> M {
let as_string = |header: Option<&hyper::header::HeaderValue>| {
header.and_then(|val| val.to_str().ok().map(|s| s.to_owned()))
header.and_then(|val| val.to_str().ok().map(ToOwned::to_owned))
};

let origin = as_string(req.headers().get("origin"));
Expand Down
27 changes: 23 additions & 4 deletions rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,25 @@
//! Parity RPC.

#![warn(missing_docs, unused_extern_crates)]
#![cfg_attr(feature = "cargo-clippy", warn(clippy::all, clippy::pedantic))]
#![cfg_attr(
feature = "cargo-clippy",
allow(
// things are often more readable this way
clippy::cast_lossless,
clippy::module_name_repetitions,
clippy::single_match_else,
clippy::type_complexity,
clippy::use_self,
// not practical
clippy::match_bool,
clippy::needless_pass_by_value,
clippy::similar_names,
// don't require markdown syntax for docs
clippy::doc_markdown,
),
warn(clippy::indexing_slicing)
)]

#[macro_use]
extern crate futures;
Expand Down Expand Up @@ -145,8 +164,8 @@ pub fn start_http<M, S, H, T>(
Ok(http::ServerBuilder::with_meta_extractor(handler, extractor)
.keep_alive(keep_alive)
.threads(threads)
.cors(cors_domains.into())
.allowed_hosts(allowed_hosts.into())
.cors(cors_domains)
.allowed_hosts(allowed_hosts)
.health_api(("/api/health", "parity_nodeStatus"))
.cors_allow_headers(AccessControlAllowHeaders::Any)
.max_request_body_size(max_payload * 1024 * 1024)
Expand Down Expand Up @@ -176,8 +195,8 @@ pub fn start_http_with_middleware<M, S, H, T, R>(
Ok(http::ServerBuilder::with_meta_extractor(handler, extractor)
.keep_alive(keep_alive)
.threads(threads)
.cors(cors_domains.into())
.allowed_hosts(allowed_hosts.into())
.cors(cors_domains)
.allowed_hosts(allowed_hosts)
.cors_allow_headers(AccessControlAllowHeaders::Any)
.max_request_body_size(max_payload * 1024 * 1024)
.request_middleware(middleware)
Expand Down
6 changes: 3 additions & 3 deletions rpc/src/tests/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ impl<T> Server<T> {

Server {
server: f(remote),
event_loop: event_loop,
event_loop,
}
}
}
Expand All @@ -60,8 +60,8 @@ pub struct GuardedAuthCodes {
pub path: PathBuf,
}

impl GuardedAuthCodes {
pub fn new() -> Self {
impl Default for GuardedAuthCodes {
fn default() -> Self {
let tempdir = TempDir::new("").unwrap();
let path = tempdir.path().join("file");

Expand Down
22 changes: 11 additions & 11 deletions rpc/src/tests/http_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ pub struct Response {
impl Response {
pub fn assert_header(&self, header: &str, value: &str) {
let header = format!("{}: {}", header, value);
assert!(self.headers.iter().find(|h| *h == &header).is_some(), "Couldn't find header {} in {:?}", header, &self.headers)
assert!(self.headers.iter().any(|h| h == &header), "Couldn't find header {} in {:?}", header, &self.headers)
}

pub fn assert_status(&self, status: &str) {
Expand Down Expand Up @@ -98,35 +98,35 @@ pub fn request(address: &SocketAddr, request: &str) -> Response {
let mut lines = response.lines();
let status = lines.next().expect("Expected a response").to_owned();
let headers_raw = read_block(&mut lines, false);
let headers = headers_raw.split('\n').map(|v| v.to_owned()).collect();
let headers = headers_raw.split('\n').map(ToOwned::to_owned).collect();
let body = read_block(&mut lines, true);

Response {
status: status,
headers: headers,
headers_raw: headers_raw,
body: body,
status,
headers,
headers_raw,
body,
}
}

/// Check if all required security headers are present
pub fn assert_security_headers_present(headers: &[String], port: Option<u16>) {
if let None = port {
if port.is_none() {
assert!(
headers.iter().find(|header| header.as_str() == "X-Frame-Options: SAMEORIGIN").is_some(),
headers.iter().any(|header| header.as_str() == "X-Frame-Options: SAMEORIGIN")
"X-Frame-Options: SAMEORIGIN missing: {:?}", headers
);
}
assert!(
headers.iter().find(|header| header.as_str() == "X-XSS-Protection: 1; mode=block").is_some(),
headers.iter().any(|header| header.as_str() == "X-XSS-Protection: 1; mode=block")
"X-XSS-Protection missing: {:?}", headers
);
assert!(
headers.iter().find(|header| header.as_str() == "X-Content-Type-Options: nosniff").is_some(),
headers.iter().any(|header| header.as_str() == "X-Content-Type-Options: nosniff")
"X-Content-Type-Options missing: {:?}", headers
);
assert!(
headers.iter().find(|header| header.starts_with("Content-Security-Policy: ")).is_some(),
headers.iter().any(|header| header.starts_with("Content-Security-Policy: "))
"Content-Security-Policy missing: {:?}", headers
)
}
2 changes: 1 addition & 1 deletion rpc/src/tests/ws.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ use tests::http_client;
pub fn serve() -> (Server<ws::Server>, usize, GuardedAuthCodes) {
let address = "127.0.0.1:0".parse().unwrap();
let io = MetaIoHandler::default();
let authcodes = GuardedAuthCodes::new();
let authcodes = GuardedAuthCodes::default();
let stats = Arc::new(informant::RpcStats::default());

let res = Server::new(|_| ::start_ws(
Expand Down
14 changes: 7 additions & 7 deletions rpc/src/v1/extractors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ impl HttpMetaExtractor for RpcExtractor {
Metadata {
origin: Origin::Rpc(
format!("{} / {}",
origin.unwrap_or("unknown origin".to_string()),
user_agent.unwrap_or("unknown agent".to_string()))
origin.unwrap_or_else(|| "unknown origin".to_string()),
user_agent.unwrap_or_else(|| "unknown agent".to_string()))
),
session: None,
}
Expand All @@ -67,7 +67,7 @@ impl WsExtractor {
/// Creates new `WsExtractor` with given authcodes path.
pub fn new(path: Option<&Path>) -> Self {
WsExtractor {
authcodes_path: path.map(|p| p.to_owned()),
authcodes_path: path.map(ToOwned::to_owned),
}
}
}
Expand All @@ -80,7 +80,7 @@ impl ws::MetaExtractor<Metadata> for WsExtractor {
Some(ref path) => {
let authorization = req.protocols.get(0).and_then(|p| auth_token_hash(&path, p, true));
match authorization {
Some(id) => Origin::Signer { session: id.into() },
Some(id) => Origin::Signer { session: id },
None => Origin::Ws { session: id.into() },
}
},
Expand Down Expand Up @@ -186,7 +186,7 @@ impl WsStats {
/// Creates new WS usage tracker.
pub fn new(stats: Arc<RpcStats>) -> Self {
WsStats {
stats: stats,
stats,
}
}
}
Expand All @@ -210,7 +210,7 @@ impl<M: core::Middleware<Metadata>> WsDispatcher<M> {
/// Create new `WsDispatcher` with given full handler.
pub fn new(full_handler: core::MetaIoHandler<Metadata, M>) -> Self {
WsDispatcher {
full_handler: full_handler,
full_handler,
}
}
}
Expand All @@ -229,7 +229,7 @@ impl<M: core::Middleware<Metadata>> core::Middleware<Metadata> for WsDispatcher<
X: core::futures::Future<Item=Option<core::Response>, Error=()> + Send + 'static,
{
let use_full = match &meta.origin {
&Origin::Signer { .. } => true,
Origin::Signer { .. } => true,
_ => false,
};

Expand Down
2 changes: 1 addition & 1 deletion rpc/src/v1/helpers/deprecated.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ impl<N: Fn() -> Instant> DeprecationNotice<N> {
pub fn print<'a, T: Into<Option<&'a str>>>(&self, method: MethodName, details: T) {
let now = (self.now)();
match self.next_warning_at.read().get(method) {
Some(next) if next > &now => return,
Some(next) if *next > now => return,
_ => {},
}

Expand Down
8 changes: 4 additions & 4 deletions rpc/src/v1/helpers/dispatch/light.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,19 +147,19 @@ where
const DEFAULT_GAS_PRICE: U256 = U256([0, 0, 0, 21_000_000]);

let gas_limit = self.client.best_block_header().gas_limit();
let request_gas_price = request.gas_price.clone();
let request_gas_price = request.gas_price;
let from = request.from.unwrap_or(default_sender);

let with_gas_price = move |gas_price| {
let request = request;
FilledTransactionRequest {
from: from.clone(),
from,
used_default_from: request.from.is_none(),
to: request.to,
nonce: request.nonce,
gas_price: gas_price,
gas_price,
gas: request.gas.unwrap_or_else(|| gas_limit / 3),
value: request.value.unwrap_or_else(|| 0.into()),
value: request.value.unwrap_or_default(),
data: request.data.unwrap_or_else(Vec::new),
condition: request.condition,
}
Expand Down
8 changes: 4 additions & 4 deletions rpc/src/v1/helpers/dispatch/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ pub fn execute<D: Dispatcher + 'static>(

Box::new(
dispatcher.sign(request, &signer, pass, post_sign).map(|(hash, token)| {
WithToken::from((ConfirmationResponse::SendTransaction(hash.into()), token))
WithToken::from((ConfirmationResponse::SendTransaction(hash), token))
})
)
},
Expand Down Expand Up @@ -368,13 +368,13 @@ pub fn from_rpc<D>(payload: RpcConfirmationPayload, default_account: Address, di
.map(ConfirmationPayload::SignTransaction))
},
RpcConfirmationPayload::Decrypt(RpcDecryptRequest { address, msg }) => {
Box::new(future::ok(ConfirmationPayload::Decrypt(address.into(), msg.into())))
Box::new(future::ok(ConfirmationPayload::Decrypt(address, msg.into())))
},
RpcConfirmationPayload::EthSignMessage(RpcEthSignRequest { address, data }) => {
Box::new(future::ok(ConfirmationPayload::EthSignMessage(address.into(), data.into())))
Box::new(future::ok(ConfirmationPayload::EthSignMessage(address, data.into())))
},
RpcConfirmationPayload::EIP191SignMessage(RpcSignRequest { address, data }) => {
Box::new(future::ok(ConfirmationPayload::SignMessage(address.into(), data.into())))
Box::new(future::ok(ConfirmationPayload::SignMessage(address, data)))
},
}
}
2 changes: 1 addition & 1 deletion rpc/src/v1/helpers/external_signer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ impl SignerService {
SignerService {
queue: Arc::new(ConfirmationsQueue::default()),
generate_new_token: Box::new(new_token),
is_enabled: is_enabled,
is_enabled,
}
}

Expand Down
2 changes: 1 addition & 1 deletion rpc/src/v1/helpers/external_signer/oneshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ pub struct Sender<T> {
impl<T> Sender<T> {
pub fn send(self, data: Res<T>) {
let res = self.sender.send(data);
if let Err(_) = res {
if res.is_err() {
debug!(target: "rpc", "Responding to a no longer active request.");
}
}
Expand Down
4 changes: 2 additions & 2 deletions rpc/src/v1/helpers/external_signer/signing_queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ impl ConfirmationsQueue {
));

// notify confirmation receiver about resolution
let result = result.ok_or(errors::request_rejected());
let result = result.ok_or_else(errors::request_rejected);
sender.sender.send(result);

Some(sender.request)
Expand Down Expand Up @@ -150,7 +150,7 @@ impl SigningQueue for ConfirmationsQueue {
// Increment id
let id = {
let mut last_id = self.id.lock();
*last_id = *last_id + U256::from(1);
*last_id += U256::from(1);
*last_id
};
// Add request to queue
Expand Down
10 changes: 5 additions & 5 deletions rpc/src/v1/helpers/fake_sign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,16 @@ pub fn sign_call(request: CallRequest) -> Result<SignedTransaction, Error> {
let max_gas = U256::from(50_000_000);
let gas = match request.gas {
Some(gas) => gas,
None => max_gas * 10u32,
None => max_gas * 10_u32,
};
let from = request.from.unwrap_or(0.into());
let from = request.from.unwrap_or_default();

Ok(Transaction {
nonce: request.nonce.unwrap_or_else(|| 0.into()),
nonce: request.nonce.unwrap_or_default(),
action: request.to.map_or(Action::Create, Action::Call),
gas,
gas_price: request.gas_price.unwrap_or_else(|| 0.into()),
value: request.value.unwrap_or(0.into()),
gas_price: request.gas_price.unwrap_or_default(),
value: request.value.unwrap_or_default(),
data: request.data.unwrap_or_default(),
}.fake_sign(from))
}
2 changes: 1 addition & 1 deletion rpc/src/v1/helpers/ipfs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,5 @@ pub fn cid(content: Bytes) -> Result<String, Error> {
let hash = digest::sha256(&content.0);
let mh = multihash::encode(multihash::Hash::SHA2256, &*hash).map_err(errors::encoding)?;
let cid = Cid::new(Codec::DagProtobuf, Version::V0, &mh);
Ok(cid.to_string().into())
Ok(cid.to_string())
}
Loading