Run latest nightly clippy

Also runs clippy on the tests and updates the CI accordingly
This commit is contained in:
Luke Parker 2023-01-01 04:18:23 -05:00
parent bff5f33616
commit 5599a052ad
No known key found for this signature in database
23 changed files with 70 additions and 73 deletions

View file

@ -26,7 +26,7 @@ jobs:
rust-components: clippy
- name: Run Clippy
run: cargo clippy --all-features -- -D warnings -A dead_code
run: cargo clippy --all-features --tests -- -D warnings -A dead_code
deny:
runs-on: ubuntu-latest

View file

@ -46,7 +46,7 @@ async fn test_ecrecover_hack() {
let keys = key_gen::<_, Secp256k1>(&mut OsRng);
let group_key = keys[&1].group_key();
const MESSAGE: &'static [u8] = b"Hello, World!";
const MESSAGE: &[u8] = b"Hello, World!";
let hashed_message = keccak256(MESSAGE);
let full_message = &[chain_id.to_be_byte_array().as_slice(), &hashed_message].concat();

View file

@ -17,7 +17,7 @@ fn test_ecrecover() {
let private = SigningKey::random(&mut OsRng);
let public = VerifyingKey::from(&private);
const MESSAGE: &'static [u8] = b"Hello, World!";
const MESSAGE: &[u8] = b"Hello, World!";
let sig: Signature = private.sign(MESSAGE);
public.verify(MESSAGE, &sig).unwrap();
@ -38,12 +38,12 @@ fn test_signing() {
let keys = key_gen::<_, Secp256k1>(&mut OsRng);
let _group_key = keys[&1].group_key();
const MESSAGE: &'static [u8] = b"Hello, World!";
const MESSAGE: &[u8] = b"Hello, World!";
let algo = Schnorr::<Secp256k1, EthereumHram>::new();
let _sig = sign(
&mut OsRng,
algo.clone(),
algo,
keys.clone(),
algorithm_machines(&mut OsRng, Schnorr::<Secp256k1, EthereumHram>::new(), &keys),
MESSAGE,
@ -64,7 +64,7 @@ fn test_ecrecover_hack() {
let group_key_compressed = group_key_encoded.as_ref();
let group_key_x = Scalar::from_uint_reduced(U256::from_be_slice(&group_key_compressed[1 .. 33]));
const MESSAGE: &'static [u8] = b"Hello, World!";
const MESSAGE: &[u8] = b"Hello, World!";
let hashed_message = keccak256(MESSAGE);
let chain_id = U256::ONE;

View file

@ -44,15 +44,14 @@ fn generators(prefix: &'static str, path: &str) {
lazy_static! {{
pub static ref GENERATORS: Generators = Generators {{
G: [
{}
{G_str}
],
H: [
{}
{H_str}
],
}};
}}
",
G_str, H_str,
)
.as_bytes(),
)

View file

@ -131,6 +131,6 @@ pub fn hash_to_scalar(data: &[u8]) -> Scalar {
// This library acknowledges its practical impossibility of it occurring, and doesn't bother to
// code in logic to handle it. That said, if it ever occurs, something must happen in order to
// not generate/verify a proof we believe to be valid when it isn't
assert!(scalar != Scalar::zero(), "ZERO HASH: {:?}", data);
assert!(scalar != Scalar::zero(), "ZERO HASH: {data:?}");
scalar
}

View file

@ -12,30 +12,30 @@ use crate::{
const SPEND: [u8; 32] = hex!("f8631661f6ab4e6fda310c797330d86e23a682f20d5bc8cc27b18051191f16d7");
const VIEW: [u8; 32] = hex!("4a1535063ad1fee2dabbf909d4fd9a873e29541b401f0944754e17c9a41820ce");
const STANDARD: &'static str =
const STANDARD: &str =
"4B33mFPMq6mKi7Eiyd5XuyKRVMGVZz1Rqb9ZTyGApXW5d1aT7UBDZ89ewmnWFkzJ5wPd2SFbn313vCT8a4E2Qf4KQH4pNey";
const PAYMENT_ID: [u8; 8] = hex!("b8963a57855cf73f");
const INTEGRATED: &'static str =
const INTEGRATED: &str =
"4Ljin4CrSNHKi7Eiyd5XuyKRVMGVZz1Rqb9ZTyGApXW5d1aT7UBDZ89ewmnWFkzJ5wPd2SFbn313vCT8a4E2Qf4KbaTH6Mn\
pXSn88oBX35";
const SUB_SPEND: [u8; 32] =
hex!("fe358188b528335ad1cfdc24a22a23988d742c882b6f19a602892eaab3c1b62b");
const SUB_VIEW: [u8; 32] = hex!("9bc2b464de90d058468522098d5610c5019c45fd1711a9517db1eea7794f5470");
const SUBADDRESS: &'static str =
const SUBADDRESS: &str =
"8C5zHM5ud8nGC4hC2ULiBLSWx9infi8JUUmWEat4fcTf8J4H38iWYVdFmPCA9UmfLTZxD43RsyKnGEdZkoGij6csDeUnbEB";
const FEATURED_JSON: &'static str = include_str!("vectors/featured_addresses.json");
const FEATURED_JSON: &str = include_str!("vectors/featured_addresses.json");
#[test]
fn standard_address() {
let addr = MoneroAddress::from_str(Network::Mainnet, STANDARD).unwrap();
assert_eq!(addr.meta.network, Network::Mainnet);
assert_eq!(addr.meta.kind, AddressType::Standard);
assert_eq!(addr.meta.kind.subaddress(), false);
assert!(!addr.meta.kind.subaddress());
assert_eq!(addr.meta.kind.payment_id(), None);
assert_eq!(addr.meta.kind.guaranteed(), false);
assert!(!addr.meta.kind.guaranteed());
assert_eq!(addr.spend.compress().to_bytes(), SPEND);
assert_eq!(addr.view.compress().to_bytes(), VIEW);
assert_eq!(addr.to_string(), STANDARD);
@ -46,9 +46,9 @@ fn integrated_address() {
let addr = MoneroAddress::from_str(Network::Mainnet, INTEGRATED).unwrap();
assert_eq!(addr.meta.network, Network::Mainnet);
assert_eq!(addr.meta.kind, AddressType::Integrated(PAYMENT_ID));
assert_eq!(addr.meta.kind.subaddress(), false);
assert!(!addr.meta.kind.subaddress());
assert_eq!(addr.meta.kind.payment_id(), Some(PAYMENT_ID));
assert_eq!(addr.meta.kind.guaranteed(), false);
assert!(!addr.meta.kind.guaranteed());
assert_eq!(addr.spend.compress().to_bytes(), SPEND);
assert_eq!(addr.view.compress().to_bytes(), VIEW);
assert_eq!(addr.to_string(), INTEGRATED);
@ -59,9 +59,9 @@ fn subaddress() {
let addr = MoneroAddress::from_str(Network::Mainnet, SUBADDRESS).unwrap();
assert_eq!(addr.meta.network, Network::Mainnet);
assert_eq!(addr.meta.kind, AddressType::Subaddress);
assert_eq!(addr.meta.kind.subaddress(), true);
assert!(addr.meta.kind.subaddress());
assert_eq!(addr.meta.kind.payment_id(), None);
assert_eq!(addr.meta.kind.guaranteed(), false);
assert!(!addr.meta.kind.guaranteed());
assert_eq!(addr.spend.compress().to_bytes(), SUB_SPEND);
assert_eq!(addr.view.compress().to_bytes(), SUB_VIEW);
assert_eq!(addr.to_string(), SUBADDRESS);

View file

@ -43,7 +43,7 @@ fn clsag() {
let dest = Zeroizing::new(random_scalar(&mut OsRng));
let mask = random_scalar(&mut OsRng);
let amount;
if i == u64::from(real) {
if i == real {
secrets = (dest.clone(), mask);
amount = AMOUNT;
} else {

View file

@ -6,8 +6,7 @@ test!(
add_single_data_less_than_255,
(
|_, mut builder: Builder, addr| async move {
// make a data that is less than 255 bytes
let arbitrary_data = Vec::from("this is an arbitrary data less than 255 bytes");
let arbitrary_data = vec![b'\0', 254];
// make sure we can add to tx
let result = builder.add_data(arbitrary_data.clone());
@ -16,11 +15,11 @@ test!(
builder.add_payment(addr, 5);
(builder.build().unwrap(), (arbitrary_data,))
},
|rpc: Rpc, signed: Transaction, mut scanner: Scanner, state: (Vec<u8>,)| async move {
|rpc: Rpc, signed: Transaction, mut scanner: Scanner, data: (Vec<u8>,)| async move {
let tx = rpc.get_transaction(signed.hash()).await.unwrap();
let output = scanner.scan_transaction(&tx).not_locked().swap_remove(0);
assert_eq!(output.commitment().amount, 5);
assert_eq!(output.arbitrary_data()[0], state.0);
assert_eq!(output.arbitrary_data()[0], data.0);
},
),
);
@ -29,26 +28,22 @@ test!(
add_multiple_data_less_than_255,
(
|_, mut builder: Builder, addr| async move {
// make a data that is less than 255 bytes
let arbitrary_data = Vec::from("this is an arbitrary data less than 255 bytes");
let data = vec![b'\0', 254];
// add tx multiple times
// Add tx multiple times
for _ in 0 .. 5 {
let result = builder.add_data(arbitrary_data.clone());
let result = builder.add_data(data.clone());
assert!(result.is_ok());
}
builder.add_payment(addr, 5);
(builder.build().unwrap(), (arbitrary_data,))
(builder.build().unwrap(), data)
},
|rpc: Rpc, signed: Transaction, mut scanner: Scanner, state: (Vec<u8>,)| async move {
|rpc: Rpc, signed: Transaction, mut scanner: Scanner, data: Vec<u8>| async move {
let tx = rpc.get_transaction(signed.hash()).await.unwrap();
let output = scanner.scan_transaction(&tx).not_locked().swap_remove(0);
assert_eq!(output.commitment().amount, 5);
let data = output.arbitrary_data();
for i in 0 .. 5 {
assert_eq!(data[i], state.0);
}
assert_eq!(output.arbitrary_data(), vec![data; 5]);
},
),
);
@ -57,23 +52,24 @@ test!(
add_single_data_more_than_255,
(
|_, mut builder: Builder, addr| async move {
// make a data that is bigger than 255 bytes
let mut arbitrary_data = vec![];
for _ in 0 .. 256 {
arbitrary_data.push(b'a');
}
// Make a data that is bigger than 255 bytes
let mut data = vec![b'a'; 256];
// make sure we get an error if we try to add it to tx
let mut result = builder.add_payment(addr, 5).add_data(arbitrary_data.clone());
assert_eq!(result, Err(TransactionError::TooMuchData));
// Make sure we get an error if we try to add it to the TX
assert_eq!(builder.add_data(data.clone()), Err(TransactionError::TooMuchData));
// reduce data size and re-try
arbitrary_data.swap_remove(0);
result = builder.add_data(arbitrary_data);
// Reduce data size and retry. The data will now be 255 bytes long, exactly
data.pop();
assert!(builder.add_data(data.clone()).is_ok());
assert!(result.is_ok());
(builder.build().unwrap(), ())
builder.add_payment(addr, 5);
(builder.build().unwrap(), data)
},
|rpc: Rpc, signed: Transaction, mut scanner: Scanner, data: Vec<u8>| async move {
let tx = rpc.get_transaction(signed.hash()).await.unwrap();
let output = scanner.scan_transaction(&tx).not_locked().swap_remove(0);
assert_eq!(output.commitment().amount, 5);
assert_eq!(output.arbitrary_data(), vec![data]);
},
|_, _, _, _| async move {},
),
);

View file

@ -1,5 +1,4 @@
use core::ops::Deref;
use std::sync::Mutex;
use lazy_static::lazy_static;
@ -8,6 +7,8 @@ use rand_core::OsRng;
use curve25519_dalek::{constants::ED25519_BASEPOINT_TABLE, scalar::Scalar};
use tokio::sync::Mutex;
use monero_serai::{
Protocol, random_scalar,
wallet::{
@ -87,7 +88,7 @@ macro_rules! async_sequential {
$(
#[tokio::test]
async fn $name() {
let guard = runner::SEQUENTIAL.lock().unwrap();
let guard = runner::SEQUENTIAL.lock().await;
let local = tokio::task::LocalSet::new();
local.run_until(async move {
if let Err(err) = tokio::task::spawn_local(async move { $body }).await {
@ -146,6 +147,7 @@ macro_rules! test {
type Builder = SignableTransactionBuilder;
// Run each function as both a single signer and as a multisig
#[allow(clippy::redundant_closure_call)]
for multisig in [false, true] {
// Only run the multisig variant if multisig is enabled
if multisig {
@ -225,7 +227,7 @@ macro_rules! test {
);
}
frost::tests::sign_without_caching(&mut OsRng, machines, &vec![])
frost::tests::sign_without_caching(&mut OsRng, machines, &[])
}
}
}

View file

@ -328,7 +328,7 @@ impl<C: Ciphersuite> Zeroize for KeyMachine<C> {
fn exponential<C: Ciphersuite>(i: u16, values: &[C::G]) -> Vec<(C::F, C::G)> {
let i = C::F::from(i.into());
let mut res = Vec::with_capacity(values.len());
(0 .. values.len()).into_iter().fold(C::F::one(), |exp, l| {
(0 .. values.len()).fold(C::F::one(), |exp, l| {
res.push((exp, values[l]));
exp * i
});

View file

@ -31,14 +31,14 @@ fn test_aos<const RING_LEN: usize>(default: Re<G0, G1>) {
ring[i] = (generators.0.alt * ring_keys[i].0, generators.1.alt * ring_keys[i].1);
}
for actual in 0 .. RING_LEN {
for (actual, key) in ring_keys.iter_mut().enumerate() {
let proof = Aos::<_, _, RING_LEN>::prove(
&mut OsRng,
transcript(),
generators,
&ring,
actual,
&mut ring_keys[actual],
key,
default.clone(),
);

View file

@ -177,7 +177,7 @@ fn test_remainder() {
// This will ignore any unused bits, ensuring every remaining one is set
let keys = mutual_scalar_from_bytes::<Scalar, Scalar>(&[0xFF; 32]);
let keys = (Zeroizing::new(keys.0), Zeroizing::new(keys.1));
assert_eq!(Scalar::one() + keys.0.deref(), Scalar::from(2u64).pow_vartime(&[255]));
assert_eq!(Scalar::one() + keys.0.deref(), Scalar::from(2u64).pow_vartime([255]));
assert_eq!(keys.0, keys.1);
let (proof, res) = ConciseLinearDLEq::prove_without_bias(

View file

@ -25,10 +25,10 @@ fn test_scalar() {
let (k, ed) = scalar_normalize::<_, DalekScalar>(initial);
// The initial scalar should equal the new scalar with Ed25519's capacity
let mut initial_bytes = (&initial.to_repr()).to_vec();
let mut initial_bytes = initial.to_repr().to_vec();
// Drop the first 4 bits to hit 252
initial_bytes[0] = initial_bytes[0] & 0b00001111;
let k_bytes = (&k.to_repr()).to_vec();
initial_bytes[0] &= 0b00001111;
let k_bytes = k.to_repr().to_vec();
assert_eq!(initial_bytes, k_bytes);
let mut ed_bytes = ed.to_repr().as_ref().to_vec();

View file

@ -129,12 +129,11 @@ pub fn test_encoding<G: PrimeGroup>() {
let bytes = point.to_bytes();
let mut repr = G::Repr::default();
repr.as_mut().copy_from_slice(bytes.as_ref());
assert_eq!(point, G::from_bytes(&repr).unwrap(), "{} couldn't be encoded and decoded", msg);
assert_eq!(point, G::from_bytes(&repr).unwrap(), "{msg} couldn't be encoded and decoded");
assert_eq!(
point,
G::from_bytes_unchecked(&repr).unwrap(),
"{} couldn't be encoded and decoded",
msg
"{msg} couldn't be encoded and decoded",
);
};
test(G::identity(), "identity");

View file

@ -43,12 +43,11 @@ pub fn test_encoding<F: PrimeField>() {
let bytes = scalar.to_repr();
let mut repr = F::Repr::default();
repr.as_mut().copy_from_slice(bytes.as_ref());
assert_eq!(scalar, F::from_repr(repr).unwrap(), "{} couldn't be encoded and decoded", msg);
assert_eq!(scalar, F::from_repr(repr).unwrap(), "{msg} couldn't be encoded and decoded");
assert_eq!(
scalar,
F::from_repr_vartime(repr).unwrap(),
"{} couldn't be encoded and decoded",
msg
"{msg} couldn't be encoded and decoded",
);
};
test(F::zero(), "0");

View file

@ -155,7 +155,7 @@ pub fn sign<R: RngCore + CryptoRng, M: PreprocessMachine>(
machines,
|rng, machines| {
// Cache and rebuild half of the machines
let mut included = machines.keys().into_iter().cloned().collect::<Vec<_>>();
let mut included = machines.keys().cloned().collect::<Vec<_>>();
for i in included.drain(..) {
if (rng.next_u64() % 2) == 0 {
let cache = machines.remove(&i).unwrap().cache();

View file

@ -56,7 +56,7 @@ impl From<serde_json::Value> for Vectors {
msg: to_str(&value["inputs"]["message"]),
included: to_str(&value["round_one_outputs"]["participant_list"])
.split(",")
.split(',')
.map(u16::from_str)
.collect::<Result<_, _>>()
.unwrap(),
@ -134,7 +134,7 @@ pub fn test_with_vectors<R: RngCore + CryptoRng, C: Curve, H: Hram<C>>(
const MSG: &[u8] = b"Hello, World!";
let (mut machines, mut shares) = commit_and_shares(&mut *rng, machines, |_, _| {}, MSG);
let faulty = *shares.keys().into_iter().next().unwrap();
let faulty = *shares.keys().next().unwrap();
shares.get_mut(&faulty).unwrap().invalidate();
for (i, machine) in machines.drain() {

View file

@ -18,6 +18,7 @@ struct LocalNetwork {
i: u16,
size: u16,
round: usize,
#[allow(clippy::type_complexity)]
rounds: Arc<RwLock<Vec<HashMap<u16, Vec<u8>>>>>,
}

View file

@ -11,7 +11,7 @@ use serai_runtime::{
pub type ChainSpec = sc_service::GenericChainSpec<GenesisConfig>;
fn insecure_pair_from_name(name: &'static str) -> Pair {
Pair::from_string(&format!("//{}", name), None).unwrap()
Pair::from_string(&format!("//{name}"), None).unwrap()
}
fn account_id_from_name(name: &'static str) -> AccountId {

View file

@ -90,6 +90,6 @@ pub fn inherent_benchmark_data() -> Result<InherentData> {
let mut inherent_data = InherentData::new();
sp_timestamp::InherentDataProvider::new(Duration::from_millis(0).into())
.provide_inherent_data(&mut inherent_data)
.map_err(|e| format!("creating inherent data: {:?}", e))?;
.map_err(|e| format!("creating inherent data: {e:?}"))?;
Ok(inherent_data)
}

View file

@ -121,7 +121,7 @@ where
return Ok((block, None));
}
self.check(&mut block).await.map_err(|e| format!("{}", e))?;
self.check(&mut block).await.map_err(|e| format!("{e}"))?;
Ok((block, None))
}
}

View file

@ -38,7 +38,7 @@ const PROTOCOL_NAME: &str = "/tendermint/1";
pub fn protocol_name<Hash: AsRef<[u8]>>(genesis: Hash, fork: Option<&str>) -> ProtocolName {
let mut name = format!("/{}", hex::encode(genesis.as_ref()));
if let Some(fork) = fork {
name += &format!("/{}", fork);
name += &format!("/{fork}");
}
name += PROTOCOL_NAME;
name.into()

View file

@ -44,7 +44,7 @@ impl SignatureScheme for TestSignatureScheme {
#[must_use]
fn verify(&self, validator: u16, msg: &[u8], sig: &[u8; 32]) -> bool {
(sig[.. 2] == validator.to_le_bytes()) && (&sig[2 ..] == &[msg, &[0; 30]].concat()[.. 30])
(sig[.. 2] == validator.to_le_bytes()) && (sig[2 ..] == [msg, &[0; 30]].concat()[.. 30])
}
fn aggregate(sigs: &[[u8; 32]]) -> Vec<[u8; 32]> {
@ -96,6 +96,7 @@ impl Block for TestBlock {
}
}
#[allow(clippy::type_complexity)]
struct TestNetwork(u16, Arc<RwLock<Vec<(MessageSender<Self>, StepSender<Self>)>>>);
#[async_trait]