Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rust 1.80+ fixes & accumulated warning cleanup #3796

Merged
merged 6 commits into from
Sep 12, 2024
Merged
Show file tree
Hide file tree
Changes from 5 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
File renamed without changes.
993 changes: 576 additions & 417 deletions Cargo.lock

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ blake2-rfc = "0.2"
chrono = "0.4.11"
clap = { version = "2.33", features = ["yaml"] }
ctrlc = { version = "3.1", features = ["termination"] }
cursive_table_view = "0.14.0"
cursive_table_view = "0.15.0"
humansize = "1.1.0"
serde = "1"
futures = "0.3.19"
Expand All @@ -42,12 +42,12 @@ grin_servers = { path = "./servers", version = "5.4.0-alpha.0" }
grin_util = { path = "./util", version = "5.4.0-alpha.0" }

[dependencies.cursive]
version = "0.20"
version = "0.21"
default-features = false
features = ["pancurses-backend"]

[build-dependencies]
built = { version = "0.4", features = ["git2"]}
built = { version = "0.7", features = ["git2"]}

[dev-dependencies]
grin_chain = { path = "./chain", version = "5.4.0-alpha.0" }
Expand Down
2 changes: 2 additions & 0 deletions chain/tests/chain_test_helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![allow(dead_code)]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is that needed for?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

there's some cargo oddness that's causing a 'not used' warning for the clean_output_dir function below during compilation, even though it's configured as test only. I spent some time trying to track it down and couldn't find a reason for it. I could possibly spend more time on it

Copy link
Contributor

@tromp tromp Sep 11, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe ask around on IRC #rust or other rust forums if other people have run into that issue. I see that googling for
rust 'not used' warning for test code
also brings up discussions on stack overflow, reddit, and the Rust programming language forum...


use self::chain::types::NoopAdapter;
use self::chain::types::Options;
Expand All @@ -29,6 +30,7 @@ use grin_keychain as keychain;
use std::fs;
use std::sync::Arc;

#[cfg(test)]
pub fn clean_output_dir(dir_name: &str) {
let _ = fs::remove_dir_all(dir_name);
}
Expand Down
14 changes: 8 additions & 6 deletions core/src/core/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ use crate::pow::{verify_size, Difficulty, Proof, ProofOfWork};
use crate::ser::{
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 keychain::{self, BlindingFactor};
use std::convert::TryInto;
Expand Down Expand Up @@ -232,7 +232,7 @@ impl Default for BlockHeader {
version: HeaderVersion(1),
height: 0,
timestamp: DateTime::from_naive_utc_and_offset(
NaiveDateTime::from_timestamp_opt(0, 0).unwrap(),
DateTime::<Utc>::from_timestamp(0, 0).unwrap().naive_utc(),
Utc,
),
prev_hash: ZERO_HASH,
Expand Down Expand Up @@ -295,25 +295,27 @@ fn read_block_header<R: Reader>(reader: &mut R) -> Result<BlockHeader, ser::Erro
> chrono::NaiveDate::MAX
.and_hms_opt(0, 0, 0)
.unwrap()
.and_utc()
.timestamp()
|| timestamp
< chrono::NaiveDate::MIN
.and_hms_opt(0, 0, 0)
.unwrap()
.and_utc()
.timestamp()
{
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() {
return Err(ser::Error::CorruptedData);
}

Ok(BlockHeader {
version,
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_root,
output_root,
Expand Down Expand Up @@ -662,12 +664,12 @@ impl Block {

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() {
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.
// Note: We have not validated the block here.
// Caller must validate the block as necessary.
Expand Down
4 changes: 0 additions & 4 deletions core/src/genesis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@
// required for genesis replacement
//! #![allow(unused_imports)]

#![cfg_attr(feature = "cargo-clippy", allow(clippy::unreadable_literal))]

use crate::core;
use crate::core::hash::Hash;
use crate::pow::{Difficulty, Proof, ProofOfWork};
Expand All @@ -44,7 +42,6 @@ pub fn genesis_dev() -> core::Block {
}

/// Testnet genesis block
#[allow(clippy::inconsistent_digit_grouping)]
pub fn genesis_test() -> core::Block {
let gen = core::Block::with_header(core::BlockHeader {
height: 0,
Expand Down Expand Up @@ -157,7 +154,6 @@ pub fn genesis_test() -> core::Block {
}

/// Mainnet genesis block
#[allow(clippy::inconsistent_digit_grouping)]
pub fn genesis_main() -> core::Block {
let gen = core::Block::with_header(core::BlockHeader {
height: 0,
Expand Down
4 changes: 2 additions & 2 deletions core/src/pow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::cuckatoo::{new_cuckatoo_ctx, CuckatooContext};
pub use crate::pow::error::Error;
use chrono::prelude::{DateTime, NaiveDateTime, Utc};
use chrono::prelude::{DateTime, Utc};

const MAX_SOLS: u32 = 10;

Expand Down Expand Up @@ -116,7 +116,7 @@ pub fn pow_size(
// well)
if bh.pow.nonce == start_nonce {
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,
);
}
Expand Down
2 changes: 0 additions & 2 deletions core/src/pow/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,6 @@ pub fn create_siphash_keys(header: &[u8]) -> Result<[u64; 4], Error> {
/// Utility struct to calculate commonly used Cuckoo parameters calculated
/// from header, nonce, edge_bits, etc.
pub struct CuckooParams {
pub edge_bits: u8,
pub proof_size: usize,
pub num_edges: u64,
pub siphash_keys: [u64; 4],
Expand All @@ -98,7 +97,6 @@ impl CuckooParams {
let num_nodes = 1u64 << node_bits;
let node_mask = num_nodes - 1;
Ok(CuckooParams {
edge_bits,
proof_size,
num_edges,
siphash_keys: [0; 4],
Expand Down
4 changes: 2 additions & 2 deletions core/tests/pmmr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,11 @@ fn bench_peak_map() {
let increments = vec![1_000_000u64, 10_000_000u64, 100_000_000u64];

for v in increments {
let start = Utc::now().timestamp_nanos();
let start = Utc::now().timestamp_nanos_opt().unwrap();
for i in 0..v {
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;
println!("{:9?} peak_map_height() in {:9.3?}ms", v, dur_ms);
}
Expand Down
33 changes: 0 additions & 33 deletions keychain/src/extkey_bip32.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@
//! Modified from above to integrate into grin and allow for different
//! hashing algorithms if desired

#[cfg(feature = "serde")]
use serde;
use std::default::Default;
use std::io::Cursor;
use std::str::FromStr;
Expand Down Expand Up @@ -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
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub enum Error {
Expand Down Expand Up @@ -875,15 +853,4 @@ mod tests {
"xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L",
"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));
}
}
6 changes: 3 additions & 3 deletions servers/src/mining/mine_block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
//! Build a block to mine: gathers transactions from the pool, assembles
//! them into a block and returns it.

use chrono::prelude::{DateTime, NaiveDateTime, Utc};
use chrono::prelude::{DateTime, Utc};
use rand::{thread_rng, Rng};
use serde_json::{json, Value};
use std::sync::Arc;
Expand Down Expand Up @@ -168,11 +168,11 @@ fn build_block(

b.header.pow.nonce = thread_rng().gen();
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() {
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!(
"Built new block with {} inputs and {} outputs, block difficulty: {}, cumulative difficulty {}",
Expand Down
6 changes: 3 additions & 3 deletions src/bin/cmd/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,15 +63,15 @@ impl HTTPNodeClient {
Err(e) => {
let report = format!("Error calling {}: {}", method, e);
error!("{}", report);
Err(Error::RPCError(report))
Err(Error::RPCError)
}
Ok(inner) => match inner.clone().into_result() {
Ok(r) => Ok(r),
Err(e) => {
error!("{:?}", inner);
let report = format!("Unable to parse response for {}: {}", method, e);
error!("{}", report);
Err(Error::RPCError(report))
Err(Error::RPCError)
}
},
}
Expand Down Expand Up @@ -251,5 +251,5 @@ pub fn client_command(client_args: &ArgMatches<'_>, global_config: GlobalConfig)
#[derive(Debug)]
enum Error {
/// RPC Error
RPCError(String),
RPCError,
}
12 changes: 7 additions & 5 deletions src/bin/tui/mining.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

use std::cmp::Ordering;

use chrono::prelude::{DateTime, NaiveDateTime, Utc};
use chrono::prelude::{DateTime, Utc};
use cursive::direction::Orientation;
use cursive::event::Key;
use cursive::traits::{Nameable, Resizable};
Expand Down Expand Up @@ -64,14 +64,15 @@ impl StratumWorkerColumn {

impl TableViewItem<StratumWorkerColumn> for WorkerStats {
fn to_column(&self, column: StratumWorkerColumn) -> String {
let naive_datetime = NaiveDateTime::from_timestamp_opt(
let naive_datetime = DateTime::<Utc>::from_timestamp(
self.last_seen
.duration_since(time::UNIX_EPOCH)
.unwrap()
.as_secs() as i64,
0,
)
.unwrap_or_default();
.unwrap_or_default()
.naive_utc();
let datetime: DateTime<Utc> = DateTime::from_naive_utc_and_offset(naive_datetime, Utc);

match column {
Expand Down Expand Up @@ -127,8 +128,9 @@ impl DiffColumn {

impl TableViewItem<DiffColumn> for DiffBlock {
fn to_column(&self, column: DiffColumn) -> String {
let naive_datetime =
NaiveDateTime::from_timestamp_opt(self.time as i64, 0).unwrap_or_default();
let naive_datetime = DateTime::<Utc>::from_timestamp(self.time as i64, 0)
.unwrap_or_default()
.naive_utc();
let datetime: DateTime<Utc> = DateTime::from_naive_utc_and_offset(naive_datetime, Utc);

match column {
Expand Down
5 changes: 1 addition & 4 deletions src/build/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,10 @@ fn main() {
}

// 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");
// don't fail the build if something's missing, may just be cargo release
let _ = built::write_built_file_with_opts(
&opts,
Path::new(env!("CARGO_MANIFEST_DIR")),
Some(Path::new(env!("CARGO_MANIFEST_DIR"))),
Path::new(&out_dir_path),
);
}
12 changes: 6 additions & 6 deletions store/tests/test_bitmap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,11 +122,11 @@ fn bench_fast_or() {

let mut bitmaps = init_bitmaps();
let mut bitmap = Bitmap::new();
let start = Utc::now().timestamp_nanos();
let start = Utc::now().timestamp_nanos_opt().unwrap();
for _ in 0..bitmaps_number {
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;
println!(
" or_inplace(): {:9.3?}ms. bitmap cardinality: {}",
Expand All @@ -135,9 +135,9 @@ fn bench_fast_or() {
);

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 fin = Utc::now().timestamp_nanos();
let fin = Utc::now().timestamp_nanos_opt().unwrap();
let dur_ms = (fin - start) as f64 * nano_to_millis;
println!(
" fast_or(): {:9.3?}ms. bitmap cardinality: {}",
Expand All @@ -146,9 +146,9 @@ fn bench_fast_or() {
);

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 fin = Utc::now().timestamp_nanos();
let fin = Utc::now().timestamp_nanos_opt().unwrap();
let dur_ms = (fin - start) as f64 * nano_to_millis;
println!(
"fast_or_heap(): {:9.3?}ms. bitmap cardinality: {}",
Expand Down
3 changes: 2 additions & 1 deletion util/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,15 @@ workspace = ".."
edition = "2018"

[dependencies]
anyhow = "1.0"
backtrace = "0.3"
base64 = "0.12"
byteorder = "1"
lazy_static = "1"
rand = "0.6"
serde = "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"
walkdir = "2"
zip = { version = "0.5.11", default-features = false }
Expand Down
Loading
Loading