Rust 1.80+ fixes & accumulated warning cleanup (#3796)

* Update versioning on master to 5.4.0-alpha.0

* updates for 1.80 and other accumulated warnings

* further warning cleanups

* move dead code tag to function defn rather than module
This commit is contained in:
Yeastplume 2024-09-12 20:59:40 +01:00 committed by GitHub
parent 845c41de13
commit 9a23cfe483
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
17 changed files with 625 additions and 502 deletions

1011
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -24,7 +24,7 @@ blake2-rfc = "0.2"
chrono = "0.4.11" chrono = "0.4.11"
clap = { version = "2.33", features = ["yaml"] } clap = { version = "2.33", features = ["yaml"] }
ctrlc = { version = "3.1", features = ["termination"] } ctrlc = { version = "3.1", features = ["termination"] }
cursive_table_view = "0.14.0" cursive_table_view = "0.15.0"
humansize = "1.1.0" humansize = "1.1.0"
serde = "1" serde = "1"
futures = "0.3.19" futures = "0.3.19"
@ -42,12 +42,12 @@ grin_servers = { path = "./servers", version = "5.4.0-alpha.0" }
grin_util = { path = "./util", version = "5.4.0-alpha.0" } grin_util = { path = "./util", version = "5.4.0-alpha.0" }
[dependencies.cursive] [dependencies.cursive]
version = "0.20" version = "0.21"
default-features = false default-features = false
features = ["pancurses-backend"] features = ["pancurses-backend"]
[build-dependencies] [build-dependencies]
built = { version = "0.4", features = ["git2"]} built = { version = "0.7", features = ["git2"]}
[dev-dependencies] [dev-dependencies]
grin_chain = { path = "./chain", version = "5.4.0-alpha.0" } grin_chain = { path = "./chain", version = "5.4.0-alpha.0" }

View file

@ -29,6 +29,8 @@ use grin_keychain as keychain;
use std::fs; use std::fs;
use std::sync::Arc; use std::sync::Arc;
#[allow(dead_code)]
#[cfg(test)]
pub fn clean_output_dir(dir_name: &str) { pub fn clean_output_dir(dir_name: &str) {
let _ = fs::remove_dir_all(dir_name); let _ = fs::remove_dir_all(dir_name);
} }

View file

@ -27,7 +27,7 @@ use crate::pow::{verify_size, Difficulty, Proof, ProofOfWork};
use crate::ser::{ use crate::ser::{
self, deserialize_default, serialize_default, PMMRable, Readable, Reader, Writeable, Writer, self, deserialize_default, serialize_default, PMMRable, Readable, Reader, Writeable, Writer,
}; };
use chrono::prelude::{DateTime, NaiveDateTime, Utc}; use chrono::prelude::{DateTime, Utc};
use chrono::Duration; use chrono::Duration;
use keychain::{self, BlindingFactor}; use keychain::{self, BlindingFactor};
use std::convert::TryInto; use std::convert::TryInto;
@ -232,7 +232,7 @@ impl Default for BlockHeader {
version: HeaderVersion(1), version: HeaderVersion(1),
height: 0, height: 0,
timestamp: DateTime::from_naive_utc_and_offset( timestamp: DateTime::from_naive_utc_and_offset(
NaiveDateTime::from_timestamp_opt(0, 0).unwrap(), DateTime::<Utc>::from_timestamp(0, 0).unwrap().naive_utc(),
Utc, Utc,
), ),
prev_hash: ZERO_HASH, prev_hash: ZERO_HASH,
@ -295,17 +295,19 @@ fn read_block_header<R: Reader>(reader: &mut R) -> Result<BlockHeader, ser::Erro
> chrono::NaiveDate::MAX > chrono::NaiveDate::MAX
.and_hms_opt(0, 0, 0) .and_hms_opt(0, 0, 0)
.unwrap() .unwrap()
.and_utc()
.timestamp() .timestamp()
|| timestamp || timestamp
< chrono::NaiveDate::MIN < chrono::NaiveDate::MIN
.and_hms_opt(0, 0, 0) .and_hms_opt(0, 0, 0)
.unwrap() .unwrap()
.and_utc()
.timestamp() .timestamp()
{ {
return Err(ser::Error::CorruptedData); return Err(ser::Error::CorruptedData);
} }
let ts = NaiveDateTime::from_timestamp_opt(timestamp, 0); let ts = DateTime::<Utc>::from_timestamp(timestamp, 0);
if ts.is_none() { if ts.is_none() {
return Err(ser::Error::CorruptedData); return Err(ser::Error::CorruptedData);
} }
@ -313,7 +315,7 @@ fn read_block_header<R: Reader>(reader: &mut R) -> Result<BlockHeader, ser::Erro
Ok(BlockHeader { Ok(BlockHeader {
version, version,
height, height,
timestamp: DateTime::from_naive_utc_and_offset(ts.unwrap(), Utc), timestamp: DateTime::from_naive_utc_and_offset(ts.unwrap().naive_utc(), Utc),
prev_hash, prev_hash,
prev_root, prev_root,
output_root, output_root,
@ -662,12 +664,12 @@ impl Block {
let now = Utc::now().timestamp(); let now = Utc::now().timestamp();
let ts = NaiveDateTime::from_timestamp_opt(now, 0); let ts = DateTime::<Utc>::from_timestamp(now, 0);
if ts.is_none() { if ts.is_none() {
return Err(Error::Other("Converting Utc::now() into timestamp".into())); return Err(Error::Other("Converting Utc::now() into timestamp".into()));
} }
let timestamp = DateTime::from_naive_utc_and_offset(ts.unwrap(), Utc); let timestamp = DateTime::from_naive_utc_and_offset(ts.unwrap().naive_utc(), Utc);
// Now build the block with all the above information. // Now build the block with all the above information.
// Note: We have not validated the block here. // Note: We have not validated the block here.
// Caller must validate the block as necessary. // Caller must validate the block as necessary.

View file

@ -17,8 +17,6 @@
// required for genesis replacement // required for genesis replacement
//! #![allow(unused_imports)] //! #![allow(unused_imports)]
#![cfg_attr(feature = "cargo-clippy", allow(clippy::unreadable_literal))]
use crate::core; use crate::core;
use crate::core::hash::Hash; use crate::core::hash::Hash;
use crate::pow::{Difficulty, Proof, ProofOfWork}; use crate::pow::{Difficulty, Proof, ProofOfWork};
@ -44,7 +42,6 @@ pub fn genesis_dev() -> core::Block {
} }
/// Testnet genesis block /// Testnet genesis block
#[allow(clippy::inconsistent_digit_grouping)]
pub fn genesis_test() -> core::Block { pub fn genesis_test() -> core::Block {
let gen = core::Block::with_header(core::BlockHeader { let gen = core::Block::with_header(core::BlockHeader {
height: 0, height: 0,
@ -157,7 +154,6 @@ pub fn genesis_test() -> core::Block {
} }
/// Mainnet genesis block /// Mainnet genesis block
#[allow(clippy::inconsistent_digit_grouping)]
pub fn genesis_main() -> core::Block { pub fn genesis_main() -> core::Block {
let gen = core::Block::with_header(core::BlockHeader { let gen = core::Block::with_header(core::BlockHeader {
height: 0, height: 0,

View file

@ -53,7 +53,7 @@ pub use crate::pow::cuckaroom::{new_cuckaroom_ctx, CuckaroomContext};
pub use crate::pow::cuckarooz::{new_cuckarooz_ctx, CuckaroozContext}; pub use crate::pow::cuckarooz::{new_cuckarooz_ctx, CuckaroozContext};
pub use crate::pow::cuckatoo::{new_cuckatoo_ctx, CuckatooContext}; pub use crate::pow::cuckatoo::{new_cuckatoo_ctx, CuckatooContext};
pub use crate::pow::error::Error; pub use crate::pow::error::Error;
use chrono::prelude::{DateTime, NaiveDateTime, Utc}; use chrono::prelude::{DateTime, Utc};
const MAX_SOLS: u32 = 10; const MAX_SOLS: u32 = 10;
@ -116,7 +116,7 @@ pub fn pow_size(
// well) // well)
if bh.pow.nonce == start_nonce { if bh.pow.nonce == start_nonce {
bh.timestamp = DateTime::from_naive_utc_and_offset( bh.timestamp = DateTime::from_naive_utc_and_offset(
NaiveDateTime::from_timestamp_opt(0, 0).unwrap(), DateTime::<Utc>::from_timestamp(0, 0).unwrap().naive_utc(),
Utc, Utc,
); );
} }

View file

@ -82,7 +82,6 @@ pub fn create_siphash_keys(header: &[u8]) -> Result<[u64; 4], Error> {
/// Utility struct to calculate commonly used Cuckoo parameters calculated /// Utility struct to calculate commonly used Cuckoo parameters calculated
/// from header, nonce, edge_bits, etc. /// from header, nonce, edge_bits, etc.
pub struct CuckooParams { pub struct CuckooParams {
pub edge_bits: u8,
pub proof_size: usize, pub proof_size: usize,
pub num_edges: u64, pub num_edges: u64,
pub siphash_keys: [u64; 4], pub siphash_keys: [u64; 4],
@ -98,7 +97,6 @@ impl CuckooParams {
let num_nodes = 1u64 << node_bits; let num_nodes = 1u64 << node_bits;
let node_mask = num_nodes - 1; let node_mask = num_nodes - 1;
Ok(CuckooParams { Ok(CuckooParams {
edge_bits,
proof_size, proof_size,
num_edges, num_edges,
siphash_keys: [0; 4], siphash_keys: [0; 4],

View file

@ -43,11 +43,11 @@ fn bench_peak_map() {
let increments = vec![1_000_000u64, 10_000_000u64, 100_000_000u64]; let increments = vec![1_000_000u64, 10_000_000u64, 100_000_000u64];
for v in increments { for v in increments {
let start = Utc::now().timestamp_nanos(); let start = Utc::now().timestamp_nanos_opt().unwrap();
for i in 0..v { for i in 0..v {
let _ = pmmr::peak_map_height(i); let _ = pmmr::peak_map_height(i);
} }
let fin = Utc::now().timestamp_nanos(); let fin = Utc::now().timestamp_nanos_opt().unwrap();
let dur_ms = (fin - start) as f64 * nano_to_millis; let dur_ms = (fin - start) as f64 * nano_to_millis;
println!("{:9?} peak_map_height() in {:9.3?}ms", v, dur_ms); println!("{:9?} peak_map_height() in {:9.3?}ms", v, dur_ms);
} }

View file

@ -30,8 +30,6 @@
//! Modified from above to integrate into grin and allow for different //! Modified from above to integrate into grin and allow for different
//! hashing algorithms if desired //! hashing algorithms if desired
#[cfg(feature = "serde")]
use serde;
use std::default::Default; use std::default::Default;
use std::io::Cursor; use std::io::Cursor;
use std::str::FromStr; use std::str::FromStr;
@ -276,26 +274,6 @@ impl fmt::Display for ChildNumber {
} }
} }
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for ChildNumber {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
u32::deserialize(deserializer).map(ChildNumber::from)
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for ChildNumber {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
u32::from(*self).serialize(serializer)
}
}
/// A BIP32 error /// A BIP32 error
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub enum Error { pub enum Error {
@ -875,15 +853,4 @@ mod tests {
"xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L", "xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L",
"xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y"); "xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y");
} }
#[test]
#[cfg(all(feature = "serde", feature = "strason"))]
pub fn encode_decode_childnumber() {
serde_round_trip!(ChildNumber::from_normal_idx(0));
serde_round_trip!(ChildNumber::from_normal_idx(1));
serde_round_trip!(ChildNumber::from_normal_idx((1 << 31) - 1));
serde_round_trip!(ChildNumber::from_hardened_idx(0));
serde_round_trip!(ChildNumber::from_hardened_idx(1));
serde_round_trip!(ChildNumber::from_hardened_idx((1 << 31) - 1));
}
} }

View file

@ -15,7 +15,7 @@
//! Build a block to mine: gathers transactions from the pool, assembles //! Build a block to mine: gathers transactions from the pool, assembles
//! them into a block and returns it. //! them into a block and returns it.
use chrono::prelude::{DateTime, NaiveDateTime, Utc}; use chrono::prelude::{DateTime, Utc};
use rand::{thread_rng, Rng}; use rand::{thread_rng, Rng};
use serde_json::{json, Value}; use serde_json::{json, Value};
use std::sync::Arc; use std::sync::Arc;
@ -168,11 +168,11 @@ fn build_block(
b.header.pow.nonce = thread_rng().gen(); b.header.pow.nonce = thread_rng().gen();
b.header.pow.secondary_scaling = difficulty.secondary_scaling; b.header.pow.secondary_scaling = difficulty.secondary_scaling;
let ts = NaiveDateTime::from_timestamp_opt(now_sec, 0); let ts = DateTime::<Utc>::from_timestamp(now_sec, 0);
if ts.is_none() { if ts.is_none() {
return Err(Error::General("Utc::now into timestamp".into())); return Err(Error::General("Utc::now into timestamp".into()));
} }
b.header.timestamp = DateTime::from_naive_utc_and_offset(ts.unwrap(), Utc); b.header.timestamp = DateTime::from_naive_utc_and_offset(ts.unwrap().naive_utc(), Utc);
debug!( debug!(
"Built new block with {} inputs and {} outputs, block difficulty: {}, cumulative difficulty {}", "Built new block with {} inputs and {} outputs, block difficulty: {}, cumulative difficulty {}",

View file

@ -63,7 +63,7 @@ impl HTTPNodeClient {
Err(e) => { Err(e) => {
let report = format!("Error calling {}: {}", method, e); let report = format!("Error calling {}: {}", method, e);
error!("{}", report); error!("{}", report);
Err(Error::RPCError(report)) Err(Error::RPCError)
} }
Ok(inner) => match inner.clone().into_result() { Ok(inner) => match inner.clone().into_result() {
Ok(r) => Ok(r), Ok(r) => Ok(r),
@ -71,7 +71,7 @@ impl HTTPNodeClient {
error!("{:?}", inner); error!("{:?}", inner);
let report = format!("Unable to parse response for {}: {}", method, e); let report = format!("Unable to parse response for {}: {}", method, e);
error!("{}", report); error!("{}", report);
Err(Error::RPCError(report)) Err(Error::RPCError)
} }
}, },
} }
@ -251,5 +251,5 @@ pub fn client_command(client_args: &ArgMatches<'_>, global_config: GlobalConfig)
#[derive(Debug)] #[derive(Debug)]
enum Error { enum Error {
/// RPC Error /// RPC Error
RPCError(String), RPCError,
} }

View file

@ -16,7 +16,7 @@
use std::cmp::Ordering; use std::cmp::Ordering;
use chrono::prelude::{DateTime, NaiveDateTime, Utc}; use chrono::prelude::{DateTime, Utc};
use cursive::direction::Orientation; use cursive::direction::Orientation;
use cursive::event::Key; use cursive::event::Key;
use cursive::traits::{Nameable, Resizable}; use cursive::traits::{Nameable, Resizable};
@ -64,14 +64,15 @@ impl StratumWorkerColumn {
impl TableViewItem<StratumWorkerColumn> for WorkerStats { impl TableViewItem<StratumWorkerColumn> for WorkerStats {
fn to_column(&self, column: StratumWorkerColumn) -> String { fn to_column(&self, column: StratumWorkerColumn) -> String {
let naive_datetime = NaiveDateTime::from_timestamp_opt( let naive_datetime = DateTime::<Utc>::from_timestamp(
self.last_seen self.last_seen
.duration_since(time::UNIX_EPOCH) .duration_since(time::UNIX_EPOCH)
.unwrap() .unwrap()
.as_secs() as i64, .as_secs() as i64,
0, 0,
) )
.unwrap_or_default(); .unwrap_or_default()
.naive_utc();
let datetime: DateTime<Utc> = DateTime::from_naive_utc_and_offset(naive_datetime, Utc); let datetime: DateTime<Utc> = DateTime::from_naive_utc_and_offset(naive_datetime, Utc);
match column { match column {
@ -127,8 +128,9 @@ impl DiffColumn {
impl TableViewItem<DiffColumn> for DiffBlock { impl TableViewItem<DiffColumn> for DiffBlock {
fn to_column(&self, column: DiffColumn) -> String { fn to_column(&self, column: DiffColumn) -> String {
let naive_datetime = let naive_datetime = DateTime::<Utc>::from_timestamp(self.time as i64, 0)
NaiveDateTime::from_timestamp_opt(self.time as i64, 0).unwrap_or_default(); .unwrap_or_default()
.naive_utc();
let datetime: DateTime<Utc> = DateTime::from_naive_utc_and_offset(naive_datetime, Utc); let datetime: DateTime<Utc> = DateTime::from_naive_utc_and_offset(naive_datetime, Utc);
match column { match column {

View file

@ -38,13 +38,10 @@ fn main() {
} }
// build and versioning information // build and versioning information
let mut opts = built::Options::default();
opts.set_dependencies(true);
let out_dir_path = format!("{}{}", env::var("OUT_DIR").unwrap(), "/built.rs"); let out_dir_path = format!("{}{}", env::var("OUT_DIR").unwrap(), "/built.rs");
// don't fail the build if something's missing, may just be cargo release // don't fail the build if something's missing, may just be cargo release
let _ = built::write_built_file_with_opts( let _ = built::write_built_file_with_opts(
&opts, Some(Path::new(env!("CARGO_MANIFEST_DIR"))),
Path::new(env!("CARGO_MANIFEST_DIR")),
Path::new(&out_dir_path), Path::new(&out_dir_path),
); );
} }

View file

@ -122,11 +122,11 @@ fn bench_fast_or() {
let mut bitmaps = init_bitmaps(); let mut bitmaps = init_bitmaps();
let mut bitmap = Bitmap::new(); let mut bitmap = Bitmap::new();
let start = Utc::now().timestamp_nanos(); let start = Utc::now().timestamp_nanos_opt().unwrap();
for _ in 0..bitmaps_number { for _ in 0..bitmaps_number {
bitmap.or_inplace(&bitmaps.pop().unwrap()); bitmap.or_inplace(&bitmaps.pop().unwrap());
} }
let fin = Utc::now().timestamp_nanos(); let fin = Utc::now().timestamp_nanos_opt().unwrap();
let dur_ms = (fin - start) as f64 * nano_to_millis; let dur_ms = (fin - start) as f64 * nano_to_millis;
println!( println!(
" or_inplace(): {:9.3?}ms. bitmap cardinality: {}", " or_inplace(): {:9.3?}ms. bitmap cardinality: {}",
@ -135,9 +135,9 @@ fn bench_fast_or() {
); );
let bitmaps = init_bitmaps(); let bitmaps = init_bitmaps();
let start = Utc::now().timestamp_nanos(); let start = Utc::now().timestamp_nanos_opt().unwrap();
let bitmap = Bitmap::fast_or(&bitmaps.iter().map(|x| x).collect::<Vec<&Bitmap>>()); let bitmap = Bitmap::fast_or(&bitmaps.iter().map(|x| x).collect::<Vec<&Bitmap>>());
let fin = Utc::now().timestamp_nanos(); let fin = Utc::now().timestamp_nanos_opt().unwrap();
let dur_ms = (fin - start) as f64 * nano_to_millis; let dur_ms = (fin - start) as f64 * nano_to_millis;
println!( println!(
" fast_or(): {:9.3?}ms. bitmap cardinality: {}", " fast_or(): {:9.3?}ms. bitmap cardinality: {}",
@ -146,9 +146,9 @@ fn bench_fast_or() {
); );
let bitmaps = init_bitmaps(); let bitmaps = init_bitmaps();
let start = Utc::now().timestamp_nanos(); let start = Utc::now().timestamp_nanos_opt().unwrap();
let bitmap = Bitmap::fast_or_heap(&bitmaps.iter().map(|x| x).collect::<Vec<&Bitmap>>()); let bitmap = Bitmap::fast_or_heap(&bitmaps.iter().map(|x| x).collect::<Vec<&Bitmap>>());
let fin = Utc::now().timestamp_nanos(); let fin = Utc::now().timestamp_nanos_opt().unwrap();
let dur_ms = (fin - start) as f64 * nano_to_millis; let dur_ms = (fin - start) as f64 * nano_to_millis;
println!( println!(
"fast_or_heap(): {:9.3?}ms. bitmap cardinality: {}", "fast_or_heap(): {:9.3?}ms. bitmap cardinality: {}",

View file

@ -10,6 +10,7 @@ workspace = ".."
edition = "2018" edition = "2018"
[dependencies] [dependencies]
anyhow = "1.0"
backtrace = "0.3" backtrace = "0.3"
base64 = "0.12" base64 = "0.12"
byteorder = "1" byteorder = "1"
@ -17,7 +18,7 @@ lazy_static = "1"
rand = "0.6" rand = "0.6"
serde = "1" serde = "1"
serde_derive = "1" serde_derive = "1"
log4rs = { version = "0.12", features = ["rolling_file_appender", "compound_policy", "size_trigger", "fixed_window_roller"] } log4rs = { version = "1.3", features = ["rolling_file_appender", "compound_policy", "size_trigger", "fixed_window_roller", "gzip"] }
log = "0.4" log = "0.4"
walkdir = "2" walkdir = "2"
zip = { version = "0.5.11", default-features = false } zip = { version = "0.5.11", default-features = false }

View file

@ -32,7 +32,6 @@ use log4rs::encode::pattern::PatternEncoder;
use log4rs::encode::writer::simple::SimpleWriter; use log4rs::encode::writer::simple::SimpleWriter;
use log4rs::encode::Encode; use log4rs::encode::Encode;
use log4rs::filter::{threshold::ThresholdFilter, Filter, Response}; use log4rs::filter::{threshold::ThresholdFilter, Filter, Response};
use std::error::Error;
use std::sync::mpsc; use std::sync::mpsc;
use std::sync::mpsc::SyncSender; use std::sync::mpsc::SyncSender;
@ -123,7 +122,7 @@ struct ChannelAppender {
} }
impl Append for ChannelAppender { impl Append for ChannelAppender {
fn append(&self, record: &Record) -> Result<(), Box<dyn Error + Sync + Send>> { fn append(&self, record: &Record) -> Result<(), anyhow::Error> {
let mut writer = SimpleWriter(Vec::new()); let mut writer = SimpleWriter(Vec::new());
self.encoder.encode(&mut writer, record)?; self.encoder.encode(&mut writer, record)?;