diff --git a/massa-api/src/public.rs b/massa-api/src/public.rs index 5256fd465fe..d80b89e153d 100644 --- a/massa-api/src/public.rs +++ b/massa-api/src/public.rs @@ -4,9 +4,7 @@ use crate::error::ApiError; use crate::{Endpoints, Public, RpcServer, StopHandle, API}; use futures::{stream::FuturesUnordered, StreamExt}; use jsonrpc_core::BoxFuture; -use massa_consensus::{ - ConsensusCommandSender, ConsensusConfig, DiscardReason, ExportBlockStatus, Status, -}; +use massa_consensus::{ConsensusCommandSender, ConsensusConfig, DiscardReason, ExportBlockStatus}; use massa_models::address::{AddressHashMap, AddressHashSet}; use massa_models::api::{ APISettings, AddressInfo, BlockInfo, BlockInfoContent, BlockSummary, EndorsementInfo, @@ -24,7 +22,7 @@ use massa_models::{ use massa_network::{NetworkCommandSender, NetworkSettings}; use massa_pool::PoolCommandSender; use massa_signature::PrivateKey; -use massa_time::UTime; +use massa_time::MassaTime; use std::net::{IpAddr, SocketAddr}; impl API { @@ -100,7 +98,7 @@ impl Endpoints for API { let node_id = self.0.node_id; let config = consensus_settings.config(); let closure = async move || { - let now = UTime::now(compensation_millis)?; + let now = MassaTime::now(compensation_millis)?; let last_slot = get_latest_block_slot_at_timestamp( consensus_settings.thread_count, consensus_settings.t0, @@ -122,8 +120,7 @@ impl Endpoints for API { connected_nodes: peers? .peers .iter() - .map(|(ip, peer)| peer.active_nodes.iter().map(move |(id, _)| (*id, *ip))) - .flatten() + .flat_map(|(ip, peer)| peer.active_nodes.iter().map(move |(id, _)| (*id, *ip))) .collect(), last_slot, next_slot: last_slot @@ -314,7 +311,7 @@ impl Endpoints for API { for (id, exported_block) in graph.active_blocks.into_iter() { res.push(BlockSummary { id, - is_final: exported_block.status == Status::Final, + is_final: exported_block.is_final, is_stale: false, is_in_blockclique: blockclique.block_ids.contains(&id), slot: exported_block.header.content.slot, @@ -357,7 +354,7 @@ impl Endpoints for API { let mut res = Vec::with_capacity(addresses.len()); // next draws info - let now = UTime::now(compensation_millis)?; + let now = MassaTime::now(compensation_millis)?; let current_slot = get_latest_block_slot_at_timestamp( cfg.thread_count, cfg.t0, @@ -442,7 +439,7 @@ impl Endpoints for API { .collect(), endorsement_draws: next_draws .iter() - .map(|(slot, (_, addrs))| { + .flat_map(|(slot, (_, addrs))| { addrs.iter().enumerate().filter_map(|(index, ad)| { if *ad == address { Some(IndexedSlot { slot: *slot, index }) @@ -451,7 +448,6 @@ impl Endpoints for API { } }) }) - .flatten() .collect(), blocks_created: blocks.remove(&address).ok_or(ApiError::NotFound)?, involved_in_endorsements: endorsements diff --git a/massa-bootstrap/src/establisher.rs b/massa-bootstrap/src/establisher.rs index 56cb42de5bf..4de7ea81752 100644 --- a/massa-bootstrap/src/establisher.rs +++ b/massa-bootstrap/src/establisher.rs @@ -1,7 +1,7 @@ // Copyright (c) 2021 MASSA LABS #[cfg(not(test))] -use massa_time::UTime; +use massa_time::MassaTime; #[cfg(not(test))] use std::{io, net::SocketAddr}; #[cfg(not(test))] @@ -45,7 +45,7 @@ impl DefaultListener { /// Initiates a connection with given timeout in millis #[cfg(not(test))] #[derive(Debug)] -pub struct DefaultConnector(UTime); +pub struct DefaultConnector(MassaTime); #[cfg(not(test))] impl DefaultConnector { @@ -86,7 +86,10 @@ impl DefaultEstablisher { /// /// # Argument /// * timeout_duration: timeout duration in millis - pub async fn get_connector(&mut self, timeout_duration: UTime) -> io::Result { + pub async fn get_connector( + &mut self, + timeout_duration: MassaTime, + ) -> io::Result { Ok(DefaultConnector(timeout_duration)) } } diff --git a/massa-bootstrap/src/lib.rs b/massa-bootstrap/src/lib.rs index f11be7957c7..395f4a7308c 100644 --- a/massa-bootstrap/src/lib.rs +++ b/massa-bootstrap/src/lib.rs @@ -11,7 +11,7 @@ use massa_logging::massa_trace; use massa_models::Version; use massa_network::{BootstrapPeers, NetworkCommandSender}; use massa_signature::{PrivateKey, PublicKey}; -use massa_time::UTime; +use massa_time::MassaTime; use messages::BootstrapMessage; use rand::{prelude::SliceRandom, rngs::StdRng, SeedableRng}; use settings::BootstrapSettings; @@ -47,7 +47,7 @@ async fn get_state_internal( let mut client = BootstrapClientBinder::new(socket, *bootstrap_public_key); // handshake - let send_time_uncompensated = UTime::now(0)?; + let send_time_uncompensated = MassaTime::now(0)?; // client.handshake() is not cancel-safe but we drop the whole client object if cancelled => it's OK match tokio::time::timeout(cfg.write_timeout.into(), client.handshake()).await { Err(_) => { @@ -87,7 +87,7 @@ async fn get_state_internal( Ok(Ok(msg)) => return Err(BootstrapError::UnexpectedMessage(msg)), }; - let recv_time_uncompensated = UTime::now(0)?; + let recv_time_uncompensated = MassaTime::now(0)?; // compute ping let ping = recv_time_uncompensated.saturating_sub(send_time_uncompensated); @@ -158,8 +158,8 @@ pub async fn get_state( bootstrap_settings: &'static BootstrapSettings, mut establisher: Establisher, version: Version, - genesis_timestamp: UTime, - end_timestamp: Option, + genesis_timestamp: MassaTime, + end_timestamp: Option, ) -> Result< ( Option, @@ -170,7 +170,7 @@ pub async fn get_state( BootstrapError, > { massa_trace!("bootstrap.lib.get_state", {}); - let now = UTime::now(0)?; + let now = MassaTime::now(0)?; // if we are before genesis, do not bootstrap if now < genesis_timestamp { massa_trace!("bootstrap.lib.get_state.init_from_scratch", {}); @@ -188,7 +188,7 @@ pub async fn get_state( loop { for (addr, pub_key) in shuffled_list.iter() { if let Some(end) = end_timestamp { - if UTime::now(0).expect("could not get now time") > end { + if MassaTime::now(0).expect("could not get now time") > end { panic!("This episode has come to an end, please get the latest testnet node version to continue"); } } @@ -410,7 +410,7 @@ async fn manage_bootstrap( }; // First, sync clocks. - let server_time = UTime::now(compensation_millis)?; + let server_time = MassaTime::now(compensation_millis)?; match tokio::time::timeout( bootstrap_settings.write_timeout.into(), server.send(messages::BootstrapMessage::BootstrapTime { diff --git a/massa-bootstrap/src/messages.rs b/massa-bootstrap/src/messages.rs index 6ea4762e792..1d5ab7150d1 100644 --- a/massa-bootstrap/src/messages.rs +++ b/massa-bootstrap/src/messages.rs @@ -5,7 +5,7 @@ use massa_models::{ DeserializeCompact, DeserializeVarInt, ModelsError, SerializeCompact, SerializeVarInt, Version, }; use massa_network::BootstrapPeers; -use massa_time::UTime; +use massa_time::MassaTime; use num_enum::{IntoPrimitive, TryFromPrimitive}; use serde::{Deserialize, Serialize}; use std::convert::TryInto; @@ -16,7 +16,7 @@ pub enum BootstrapMessage { /// Sync clocks, BootstrapTime { /// The current time on the bootstrap server. - server_time: UTime, + server_time: MassaTime, version: Version, }, /// Sync clocks, @@ -80,7 +80,7 @@ impl DeserializeCompact for BootstrapMessage { let res = match type_id { MessageTypeId::BootstrapTime => { - let (server_time, delta) = UTime::from_bytes_compact(&buffer[cursor..])?; + let (server_time, delta) = MassaTime::from_bytes_compact(&buffer[cursor..])?; cursor += delta; let (version, delta) = Version::from_bytes_compact(&buffer[cursor..])?; diff --git a/massa-bootstrap/src/settings.rs b/massa-bootstrap/src/settings.rs index 8e5ca8412c2..761da65a5a3 100644 --- a/massa-bootstrap/src/settings.rs +++ b/massa-bootstrap/src/settings.rs @@ -1,7 +1,7 @@ // Copyright (c) 2021 MASSA LABS use massa_signature::PublicKey; -use massa_time::UTime; +use massa_time::MassaTime; use serde::Deserialize; use std::net::SocketAddr; @@ -35,23 +35,23 @@ pub struct BootstrapSettings { /// Port to listen if we choose to allow other nodes to use us as bootstrap node. pub bind: Option, /// connection timeout - pub connect_timeout: UTime, + pub connect_timeout: MassaTime, /// readout timeout - pub read_timeout: UTime, + pub read_timeout: MassaTime, /// write timeout - pub write_timeout: UTime, + pub write_timeout: MassaTime, /// Time we wait before retrying a bootstrap - pub retry_delay: UTime, + pub retry_delay: MassaTime, /// Max ping delay. - pub max_ping: UTime, + pub max_ping: MassaTime, /// Enable clock synchronization pub enable_clock_synchronization: bool, /// Cache duration - pub cache_duration: UTime, + pub cache_duration: MassaTime, /// Max simultaneous bootstraps pub max_simultaneous_bootstraps: u32, /// Minimum interval between two bootstrap attempts from a given IP - pub per_ip_min_interval: UTime, + pub per_ip_min_interval: MassaTime, /// Max size of the IP list pub ip_list_max_size: usize, } diff --git a/massa-bootstrap/src/tests/mock_establisher.rs b/massa-bootstrap/src/tests/mock_establisher.rs index e99a362ea35..c3825f6f9c0 100644 --- a/massa-bootstrap/src/tests/mock_establisher.rs +++ b/massa-bootstrap/src/tests/mock_establisher.rs @@ -1,6 +1,6 @@ // Copyright (c) 2021 MASSA LABS -use massa_time::UTime; +use massa_time::MassaTime; use std::io; use std::net::SocketAddr; use tokio::io::DuplexStream; @@ -59,7 +59,7 @@ impl MockListener { #[derive(Debug)] pub struct MockConnector { connection_connector_tx: mpsc::Sender<(Duplex, SocketAddr, oneshot::Sender)>, - timeout_duration: UTime, + timeout_duration: MassaTime, } impl MockConnector { @@ -117,7 +117,7 @@ impl MockEstablisher { pub async fn get_connector( &mut self, - timeout_duration: UTime, + timeout_duration: MassaTime, ) -> std::io::Result { // create connector stream diff --git a/massa-bootstrap/src/tests/scenarios.rs b/massa-bootstrap/src/tests/scenarios.rs index 98bf2d34342..2dce22ce7b2 100644 --- a/massa-bootstrap/src/tests/scenarios.rs +++ b/massa-bootstrap/src/tests/scenarios.rs @@ -16,7 +16,7 @@ use massa_consensus::{ConsensusCommand, ConsensusCommandSender}; use massa_models::Version; use massa_network::{NetworkCommand, NetworkCommandSender}; use massa_signature::PrivateKey; -use massa_time::UTime; +use massa_time::MassaTime; use serial_test::serial; use std::str::FromStr; use tokio::sync::mpsc; @@ -58,7 +58,7 @@ async fn test_bootstrap_server() { bootstrap_settings, remote_establisher, Version::from_str("TEST.1.2").unwrap(), - UTime::now(0).unwrap().saturating_sub(1000.into()), + MassaTime::now(0).unwrap().saturating_sub(1000.into()), None, ) .await diff --git a/massa-bootstrap/src/tests/tools.rs b/massa-bootstrap/src/tests/tools.rs index 21ff3e25455..9e5f05329fe 100644 --- a/massa-bootstrap/src/tests/tools.rs +++ b/massa-bootstrap/src/tests/tools.rs @@ -20,7 +20,7 @@ use massa_network::{BootstrapPeers, NetworkCommand}; use massa_signature::{ derive_public_key, generate_random_private_key, sign, PrivateKey, PublicKey, Signature, }; -use massa_time::UTime; +use massa_time::MassaTime; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::str::FromStr; use tokio::io::AsyncReadExt; @@ -75,7 +75,7 @@ pub fn get_bootstrap_config(bootstrap_public_key: PublicKey) -> BootstrapSetting bind: Some("0.0.0.0:31244".parse().unwrap()), connect_timeout: 200.into(), retry_delay: 200.into(), - max_ping: UTime::from(500), + max_ping: MassaTime::from(500), read_timeout: 1000.into(), write_timeout: 1000.into(), bootstrap_list: vec![(SocketAddr::new(BASE_BOOTSTRAP_IP, 16), bootstrap_public_key)], @@ -95,7 +95,7 @@ pub fn get_keys() -> (PrivateKey, PublicKey) { pub async fn wait_consensus_command( consensus_command_receiver: &mut Receiver, - timeout: UTime, + timeout: MassaTime, filter_map: F, ) -> Option where @@ -116,7 +116,7 @@ where pub async fn wait_network_command( network_command_receiver: &mut Receiver, - timeout: UTime, + timeout: MassaTime, filter_map: F, ) -> Option where diff --git a/massa-client/src/cmds.rs b/massa-client/src/cmds.rs index 91ecb0d95b1..9b94c3249d7 100644 --- a/massa-client/src/cmds.rs +++ b/massa-client/src/cmds.rs @@ -11,7 +11,7 @@ use massa_models::{ Address, Amount, BlockId, EndorsementId, OperationContent, OperationId, OperationType, Slot, }; use massa_signature::{generate_random_private_key, PrivateKey, PublicKey}; -use massa_time::UTime; +use massa_time::MassaTime; use massa_wallet::Wallet; use serde::Serialize; use std::collections::HashMap; @@ -190,7 +190,7 @@ impl Display for ExtendedWalletEntry { pub struct ExtendedWallet(AddressHashMap); impl ExtendedWallet { - fn new(wallet: &Wallet, addresses_info: &Vec) -> Result { + fn new(wallet: &Wallet, addresses_info: &[AddressInfo]) -> Result { Ok(ExtendedWallet( addresses_info .iter() @@ -245,7 +245,7 @@ impl Command { &self, client: &Client, wallet: &mut Wallet, - parameters: &Vec, + parameters: &[String], json: bool, ) -> Result> { match self { @@ -603,8 +603,9 @@ impl Command { Ok(node_status) => node_status.consensus_stats.end_timespan, Err(e) => bail!("RpcError: {}", e), }; - let (days, hours, mins, secs) = - end.saturating_sub(UTime::now(0)?).days_hours_mins_secs()?; // compensation millis is zero + let (days, hours, mins, secs) = end + .saturating_sub(MassaTime::now(0)?) + .days_hours_mins_secs()?; // compensation millis is zero let mut res = "".to_string(); res.push_str(&format!("{} days, {} hours, {} minutes, {} seconds remaining until the end of the current episode", days, hours, mins, secs)); if !json { @@ -663,6 +664,6 @@ async fn send_operation( } // TODO: ugly utilities functions -pub fn parse_vec(args: &Vec) -> anyhow::Result, T::Err> { +pub fn parse_vec(args: &[String]) -> anyhow::Result, T::Err> { args.iter().map(|x| x.parse::()).collect() } diff --git a/massa-client/src/tests/tools.rs b/massa-client/src/tests/tools.rs index 5e6acaeafd2..57d9089fe50 100644 --- a/massa-client/src/tests/tools.rs +++ b/massa-client/src/tests/tools.rs @@ -1,6 +1,6 @@ extern crate toml_edit; -use massa_time::UTime; +use massa_time::MassaTime; use std::fs; use toml_edit::{value, Document}; @@ -9,7 +9,7 @@ pub fn _update_genesis_timestamp(config_path: &str) { let mut doc = toml.parse::().unwrap(); doc["consensus"]["genesis_timestamp"] = value(format!( "{}", - UTime::now(10000 * 60 * 60).unwrap().to_millis() + MassaTime::now(10000 * 60 * 60).unwrap().to_millis() )); fs::write(config_path, doc.to_string()).expect("Unable to write file"); } diff --git a/massa-consensus/src/block_graph.rs b/massa-consensus/src/block_graph.rs index f3014b5aaed..774e07b9cbc 100644 --- a/massa-consensus/src/block_graph.rs +++ b/massa-consensus/src/block_graph.rs @@ -551,7 +551,7 @@ pub struct ExportCompiledBlock { /// in thread i. pub children: Vec, /// Active or final - pub status: Status, + pub is_final: bool, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] @@ -617,11 +617,7 @@ impl<'a> BlockGraphExport { .iter() .map(|thread| thread.keys().copied().collect::()) .collect(), - status: if a_block.is_final { - Status::Final - } else { - Status::Active - }, + is_final: a_block.is_final, }, ); } diff --git a/massa-consensus/src/consensus_worker.rs b/massa-consensus/src/consensus_worker.rs index b6f40c9f365..b645fe4b6ab 100644 --- a/massa-consensus/src/consensus_worker.rs +++ b/massa-consensus/src/consensus_worker.rs @@ -29,7 +29,7 @@ use massa_models::{ use massa_pool::PoolCommandSender; use massa_protocol_exports::{ProtocolCommandSender, ProtocolEvent, ProtocolEventReceiver}; use massa_signature::{derive_public_key, PrivateKey, PublicKey}; -use massa_time::UTime; +use massa_time::MassaTime; use std::{cmp::max, collections::HashSet, collections::VecDeque}; use tokio::{ sync::{mpsc, mpsc::error::SendTimeoutError, oneshot}, @@ -151,11 +151,11 @@ pub struct ConsensusWorker { // staking keys staking_keys: AddressHashMap<(PublicKey, PrivateKey)>, // stats (block -> tx_count, creator) - final_block_stats: VecDeque<(UTime, u64, Address)>, - stale_block_stats: VecDeque, - stats_history_timespan: UTime, - stats_desync_detection_timespan: UTime, - launch_time: UTime, + final_block_stats: VecDeque<(MassaTime, u64, Address)>, + stale_block_stats: VecDeque, + stats_history_timespan: MassaTime, + stats_desync_detection_timespan: MassaTime, + launch_time: MassaTime, // endorsed slots cache endorsed_slots: HashSet, } @@ -186,7 +186,7 @@ impl ConsensusWorker { clock_compensation: i64, staking_keys: AddressHashMap<(PublicKey, PrivateKey)>, ) -> Result { - let now = UTime::now(clock_compensation)?; + let now = MassaTime::now(clock_compensation)?; let previous_slot = get_latest_block_slot_at_timestamp( cfg.thread_count, cfg.t0, @@ -267,7 +267,7 @@ impl ConsensusWorker { stats_desync_detection_timespan, stats_history_timespan: max(stats_desync_detection_timespan, cfg.stats_timespan), cfg, - launch_time: UTime::now(clock_compensation)?, + launch_time: MassaTime::now(clock_compensation)?, endorsed_slots: HashSet::new(), execution_event_receiver, }) @@ -336,7 +336,7 @@ impl ConsensusWorker { _ = &mut next_slot_timer => { massa_trace!("consensus.consensus_worker.run_loop.select.slot_tick", {}); if let Some(end) = self.cfg.end_timestamp { - if UTime::now(self.clock_compensation)? > end { + if MassaTime::now(self.clock_compensation)? > end { info!("This episode has come to an end, please get the latest testnet node version to continue"); break; } @@ -372,7 +372,7 @@ impl ConsensusWorker { &mut self, next_slot_timer: &mut std::pin::Pin<&mut Sleep>, ) -> Result<(), ConsensusError> { - let now = UTime::now(self.clock_compensation)?; + let now = MassaTime::now(self.clock_compensation)?; let observed_slot = get_latest_block_slot_at_timestamp( self.cfg.thread_count, self.cfg.t0, @@ -1039,7 +1039,7 @@ impl ConsensusWorker { } fn get_stats(&mut self) -> Result { - let timespan_end = max(self.launch_time, UTime::now(self.clock_compensation)?); + let timespan_end = max(self.launch_time, MassaTime::now(self.clock_compensation)?); let timespan_start = max( timespan_end.saturating_sub(self.cfg.stats_timespan), self.launch_time, @@ -1245,7 +1245,7 @@ impl ConsensusWorker { // prune statistics fn prune_stats(&mut self) -> Result<(), ConsensusError> { let start_time = - UTime::now(self.clock_compensation)?.saturating_sub(self.stats_history_timespan); + MassaTime::now(self.clock_compensation)?.saturating_sub(self.stats_history_timespan); self.final_block_stats.retain(|(t, _, _)| t >= &start_time); self.stale_block_stats.retain(|t| t >= &start_time); Ok(()) @@ -1307,7 +1307,7 @@ impl ConsensusWorker { new_final_block_ids.len(), BuildHHasher::default(), ); - let timestamp = UTime::now(self.clock_compensation)?; + let timestamp = MassaTime::now(self.clock_compensation)?; for b_id in new_final_block_ids.into_iter() { if let Some(a_block) = self.block_db.get_active_block(&b_id) { // List new final ops @@ -1432,7 +1432,7 @@ impl ConsensusWorker { // add stale blocks to stats let new_stale_block_ids_creators_slots = self.block_db.get_new_stale_blocks(); - let timestamp = UTime::now(self.clock_compensation)?; + let timestamp = MassaTime::now(self.clock_compensation)?; for (b_id, (b_creator, b_slot)) in new_stale_block_ids_creators_slots.into_iter() { self.stale_block_stats.push_back(timestamp); diff --git a/massa-consensus/src/pos.rs b/massa-consensus/src/pos.rs index a1d719b76f9..1d09b12af8f 100644 --- a/massa-consensus/src/pos.rs +++ b/massa-consensus/src/pos.rs @@ -78,21 +78,27 @@ impl RollUpdate { self.roll_purchases = self .roll_purchases .checked_add(change.roll_purchases - compensation_other) - .ok_or(ConsensusError::InvalidRollUpdate( - "roll_purchases overflow in RollUpdate::chain".into(), - ))?; + .ok_or_else(|| { + ConsensusError::InvalidRollUpdate( + "roll_purchases overflow in RollUpdate::chain".into(), + ) + })?; self.roll_sales = self .roll_sales .checked_add(change.roll_sales - compensation_other) - .ok_or(ConsensusError::InvalidRollUpdate( - "roll_sales overflow in RollUpdate::chain".into(), - ))?; + .ok_or_else(|| { + ConsensusError::InvalidRollUpdate("roll_sales overflow in RollUpdate::chain".into()) + })?; let compensation_self = self.compensate().0; - let compensation_total = compensation_other.checked_add(compensation_self).ok_or( - ConsensusError::InvalidRollUpdate("compensation overflow in RollUpdate::chain".into()), - )?; + let compensation_total = compensation_other + .checked_add(compensation_self) + .ok_or_else(|| { + ConsensusError::InvalidRollUpdate( + "compensation overflow in RollUpdate::chain".into(), + ) + })?; Ok(RollCompensation(compensation_total)) } @@ -190,6 +196,10 @@ impl RollCounts { self.0.len() } + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + /// applies RollUpdates to self with compensations pub fn apply_updates(&mut self, updates: &RollUpdates) -> Result<(), ConsensusError> { for (addr, update) in updates.0.iter() { @@ -199,15 +209,19 @@ impl RollCounts { if update.roll_purchases >= update.roll_sales { *occ.get_mut() = cur_val .checked_add(update.roll_purchases - update.roll_sales) - .ok_or(ConsensusError::InvalidRollUpdate( - "overflow while incrementing roll count".into(), - ))?; + .ok_or_else(|| { + ConsensusError::InvalidRollUpdate( + "overflow while incrementing roll count".into(), + ) + })?; } else { *occ.get_mut() = cur_val .checked_sub(update.roll_sales - update.roll_purchases) - .ok_or(ConsensusError::InvalidRollUpdate( - "underflow while decrementing roll count".into(), - ))?; + .ok_or_else(|| { + ConsensusError::InvalidRollUpdate( + "underflow while decrementing roll count".into(), + ) + })?; } if *occ.get() == 0 { // remove if 0 diff --git a/massa-consensus/src/settings.rs b/massa-consensus/src/settings.rs index 515b8bac9e6..4ca60fb2cf0 100644 --- a/massa-consensus/src/settings.rs +++ b/massa-consensus/src/settings.rs @@ -4,7 +4,7 @@ use massa_models::{Amount, Config}; #[allow(unused_imports)] use massa_signature::generate_random_private_key; use massa_signature::PrivateKey; -use massa_time::UTime; +use massa_time::MassaTime; use num::rational::Ratio; use serde::{Deserialize, Serialize}; #[allow(unused_imports)] @@ -16,13 +16,13 @@ pub const CHANNEL_SIZE: usize = 256; #[cfg(not(test))] lazy_static::lazy_static! { /// Time in millis when the blockclique started. - pub static ref GENESIS_TIMESTAMP: UTime = 1638460800000.into(); + pub static ref GENESIS_TIMESTAMP: MassaTime = 1638460800000.into(); /// TESTNET: time when the blockclique is ended. - pub static ref END_TIMESTAMP: Option = Some(1640883600000.into()); + pub static ref END_TIMESTAMP: Option = Some(1640883600000.into()); /// Time between the periods in the same thread. - pub static ref T0: UTime = 16000.into(); + pub static ref T0: MassaTime = 16000.into(); /// Private_key to sign genesis blocks. pub static ref GENESIS_KEY: PrivateKey = "SGoTK5TJ9ZcCgQVmdfma88UdhS6GK94aFEYAsU3F1inFayQ6S" @@ -42,13 +42,13 @@ lazy_static::lazy_static! { #[cfg(test)] lazy_static::lazy_static! { /// Time in millis when the blockclique started. - pub static ref GENESIS_TIMESTAMP: UTime = UTime::now(0).unwrap(); + pub static ref GENESIS_TIMESTAMP: MassaTime = MassaTime::now(0).unwrap(); /// TESTNET: time when the blockclique is ended. - pub static ref END_TIMESTAMP: Option = None; + pub static ref END_TIMESTAMP: Option = None; /// Time between the periods in the same thread. - pub static ref T0: UTime = 32000.into(); + pub static ref T0: MassaTime = 32000.into(); /// Private_key to sign genesis blocks. pub static ref GENESIS_KEY: PrivateKey = generate_random_private_key(); @@ -139,18 +139,18 @@ pub struct ConsensusSettings { /// path to ledger db pub ledger_path: PathBuf, pub ledger_cache_capacity: u64, - pub ledger_flush_interval: Option, + pub ledger_flush_interval: Option, pub ledger_reset_at_startup: bool, pub initial_ledger_path: PathBuf, pub operation_batch_size: usize, pub initial_rolls_path: PathBuf, // stats timespan - pub stats_timespan: UTime, + pub stats_timespan: MassaTime, // max event send wait - pub max_send_wait: UTime, + pub max_send_wait: MassaTime, // force keep at least this number of final periods in RAM for each thread pub force_keep_final_periods: u64, - pub block_db_prune_interval: UTime, + pub block_db_prune_interval: MassaTime, pub max_item_return_count: usize, /// If we want to generate blocks. /// Parameter that shouldn't be defined in prod. @@ -207,13 +207,13 @@ impl ConsensusSettings { #[derive(Debug, Deserialize, Serialize, Clone)] pub struct ConsensusConfig { /// Time in millis when the blockclique started. - pub genesis_timestamp: UTime, + pub genesis_timestamp: MassaTime, /// TESTNET: time when the blockclique is ended. - pub end_timestamp: Option, + pub end_timestamp: Option, /// Number of threads pub thread_count: u8, /// Time between the periods in the same thread. - pub t0: UTime, + pub t0: MassaTime, /// Private_key to sign genesis blocks. pub genesis_key: PrivateKey, /// Staking private keys @@ -249,7 +249,7 @@ pub struct ConsensusConfig { /// path to ledger db pub ledger_path: PathBuf, pub ledger_cache_capacity: u64, - pub ledger_flush_interval: Option, + pub ledger_flush_interval: Option, pub ledger_reset_at_startup: bool, pub initial_ledger_path: PathBuf, pub block_reward: Amount, @@ -258,13 +258,13 @@ pub struct ConsensusConfig { pub initial_draw_seed: String, pub roll_price: Amount, /// stats timespan - pub stats_timespan: UTime, + pub stats_timespan: MassaTime, /// max event send wait - pub max_send_wait: UTime, + pub max_send_wait: MassaTime, /// force keep at least this number of final periods in RAM for each thread pub force_keep_final_periods: u64, pub endorsement_count: u32, - pub block_db_prune_interval: UTime, + pub block_db_prune_interval: MassaTime, pub max_item_return_count: usize, /// If we want to generate blocks. /// Parameter that shouldn't be defined in prod. diff --git a/massa-consensus/src/tests/block_factory.rs b/massa-consensus/src/tests/block_factory.rs index 2c05a02953c..9d901ec0024 100644 --- a/massa-consensus/src/tests/block_factory.rs +++ b/massa-consensus/src/tests/block_factory.rs @@ -44,8 +44,7 @@ impl BlockFactory { &self .operations .iter() - .map(|op| op.get_operation_id().unwrap().to_bytes()) - .flatten() + .flat_map(|op| op.get_operation_id().unwrap().to_bytes()) .collect::>()[..], ), endorsements: self.endorsements.clone(), diff --git a/massa-consensus/src/tests/mock_pool_controller.rs b/massa-consensus/src/tests/mock_pool_controller.rs index 4d951c31a4e..6024f33fcae 100644 --- a/massa-consensus/src/tests/mock_pool_controller.rs +++ b/massa-consensus/src/tests/mock_pool_controller.rs @@ -1,7 +1,7 @@ // Copyright (c) 2021 MASSA LABS use massa_pool::{PoolCommand, PoolCommandSender}; -use massa_time::UTime; +use massa_time::MassaTime; use tokio::{ sync::{mpsc, oneshot}, task::JoinHandle, @@ -23,7 +23,7 @@ impl MockPoolController { ) } - pub async fn wait_command(&mut self, timeout: UTime, filter_map: F) -> Option + pub async fn wait_command(&mut self, timeout: MassaTime, filter_map: F) -> Option where F: Fn(PoolCommand) -> Option, { diff --git a/massa-consensus/src/tests/mock_protocol_controller.rs b/massa-consensus/src/tests/mock_protocol_controller.rs index 0c9139dd1ea..82a1df979a0 100644 --- a/massa-consensus/src/tests/mock_protocol_controller.rs +++ b/massa-consensus/src/tests/mock_protocol_controller.rs @@ -4,7 +4,7 @@ use massa_models::{Block, BlockHeader, BlockId}; use massa_protocol_exports::{ ProtocolCommand, ProtocolCommandSender, ProtocolEvent, ProtocolEventReceiver, }; -use massa_time::UTime; +use massa_time::MassaTime; use tokio::{sync::mpsc, time::sleep}; const CHANNEL_SIZE: usize = 256; @@ -29,7 +29,7 @@ impl MockProtocolController { ) } - pub async fn wait_command(&mut self, timeout: UTime, filter_map: F) -> Option + pub async fn wait_command(&mut self, timeout: MassaTime, filter_map: F) -> Option where F: Fn(ProtocolCommand) -> Option, { diff --git a/massa-consensus/src/tests/scenario_block_creation.rs b/massa-consensus/src/tests/scenario_block_creation.rs index 8ebc8231dbc..f7bb40431c7 100644 --- a/massa-consensus/src/tests/scenario_block_creation.rs +++ b/massa-consensus/src/tests/scenario_block_creation.rs @@ -13,7 +13,7 @@ use massa_models::{Endorsement, SerializeCompact}; use massa_pool::PoolCommand; use massa_protocol_exports::ProtocolCommand; use massa_signature::{derive_public_key, generate_random_private_key, PrivateKey}; -use massa_time::UTime; +use massa_time::MassaTime; use serial_test::serial; use std::collections::HashMap; use std::str::FromStr; @@ -74,7 +74,7 @@ async fn test_genesis_block_creation() { ); // Set genesis timestamp. - cfg.genesis_timestamp = UTime::from_str("1633301290000").unwrap(); + cfg.genesis_timestamp = MassaTime::from_str("1633301290000").unwrap(); tools::consensus_without_pool_test( cfg.clone(), @@ -155,7 +155,7 @@ async fn test_block_creation_with_draw() { cfg.pos_lookback_cycles = 2; cfg.thread_count = thread_count; cfg.delta_f0 = 3; - cfg.genesis_timestamp = UTime::now(0) + cfg.genesis_timestamp = MassaTime::now(0) .unwrap() .checked_sub((cfg.t0.to_millis() * cfg.periods_per_cycle * 3).into()) .unwrap() @@ -318,7 +318,7 @@ async fn test_interleaving_block_creation_with_reception() { ); cfg.t0 = 1000.into(); cfg.thread_count = thread_count; - cfg.genesis_timestamp = UTime::now(0).unwrap().checked_add(1000.into()).unwrap(); + cfg.genesis_timestamp = MassaTime::now(0).unwrap().checked_add(1000.into()).unwrap(); cfg.disable_block_creation = false; tools::consensus_without_pool_test( @@ -464,7 +464,7 @@ async fn test_order_of_inclusion() { cfg.operation_batch_size = 3; cfg.max_operations_per_block = 50; // Increase timestamp a bit to avoid missing the first slot. - cfg.genesis_timestamp = UTime::now(0).unwrap().checked_add(1000.into()).unwrap(); + cfg.genesis_timestamp = MassaTime::now(0).unwrap().checked_add(1000.into()).unwrap(); let op1 = create_transaction(priv_a, pubkey_a, address_b, 5, 10, 1); let op2 = create_transaction(priv_a, pubkey_a, address_b, 50, 10, 10); diff --git a/massa-consensus/src/tests/scenario_roll.rs b/massa-consensus/src/tests/scenario_roll.rs index d2f95e019f3..72369cdcdd2 100644 --- a/massa-consensus/src/tests/scenario_roll.rs +++ b/massa-consensus/src/tests/scenario_roll.rs @@ -5,7 +5,7 @@ use massa_models::{Address, Amount, BlockId, Slot}; use massa_pool::PoolCommand; use massa_protocol_exports::ProtocolCommand; use massa_signature::{derive_public_key, generate_random_private_key}; -use massa_time::UTime; +use massa_time::MassaTime; use num::rational::Ratio; use rand::{prelude::SliceRandom, rngs::StdRng, SeedableRng}; use serial_test::serial; @@ -85,7 +85,7 @@ async fn test_roll() { cfg.block_reward = Amount::default(); cfg.roll_price = Amount::from_str("1000").unwrap(); cfg.operation_validity_periods = 100; - cfg.genesis_timestamp = UTime::now(0).unwrap().saturating_add(300.into()); + cfg.genesis_timestamp = MassaTime::now(0).unwrap().saturating_add(300.into()); tools::consensus_pool_test( cfg.clone(), @@ -544,7 +544,7 @@ async fn test_roll_block_creation() { let (mut _execution_controller, execution_command_sender, execution_event_receiver) = MockExecutionController::new(); - cfg.genesis_timestamp = UTime::now(0).unwrap().saturating_add(300.into()); + cfg.genesis_timestamp = MassaTime::now(0).unwrap().saturating_add(300.into()); // launch consensus controller let (consensus_command_sender, _consensus_event_receiver, _consensus_manager) = start_consensus_controller( @@ -862,7 +862,7 @@ async fn test_roll_deactivation() { let (mut pool_controller, pool_command_sender) = MockPoolController::new(); let (mut _execution_controller, execution_command_sender, execution_event_receiver) = MockExecutionController::new(); - cfg.genesis_timestamp = UTime::now(0).unwrap().saturating_add(300.into()); + cfg.genesis_timestamp = MassaTime::now().unwrap().saturating_add(300.into()); // launch consensus controller let (consensus_command_sender, _consensus_event_receiver, _consensus_manager) = start_consensus_controller( diff --git a/massa-consensus/src/tests/scenarios106.rs b/massa-consensus/src/tests/scenarios106.rs index 3c573fd8c50..53aba9c45ce 100644 --- a/massa-consensus/src/tests/scenarios106.rs +++ b/massa-consensus/src/tests/scenarios106.rs @@ -6,7 +6,7 @@ use crate::tests::tools::{self, generate_ledger_file}; use massa_models::timeslots; use massa_models::{BlockHashSet, BlockId, Slot}; use massa_signature::{generate_random_private_key, PrivateKey}; -use massa_time::UTime; +use massa_time::MassaTime; use serial_test::serial; use std::collections::{HashMap, HashSet}; @@ -163,7 +163,7 @@ async fn test_unsorted_block_with_to_much_in_the_future() { staking_file.path(), ); cfg.t0 = 1000.into(); - cfg.genesis_timestamp = UTime::now(0).unwrap().saturating_sub(2000.into()); // slot 1 is in the past + cfg.genesis_timestamp = MassaTime::now(0).unwrap().saturating_sub(2000.into()); // slot 1 is in the past cfg.future_block_processing_max_periods = 3; cfg.max_future_processing_blocks = 5; @@ -266,7 +266,7 @@ async fn test_too_many_blocks_in_the_future() { cfg.future_block_processing_max_periods = 100; cfg.max_future_processing_blocks = 2; cfg.delta_f0 = 1000; - cfg.genesis_timestamp = UTime::now(0).unwrap().saturating_sub(2000.into()); // slot 1 is in the past + cfg.genesis_timestamp = MassaTime::now(0).unwrap().saturating_sub(2000.into()); // slot 1 is in the past tools::consensus_without_pool_test( cfg.clone(), @@ -367,7 +367,7 @@ async fn test_dep_in_back_order() { staking_file.path(), ); cfg.t0 = 1000.into(); - cfg.genesis_timestamp = UTime::now(0) + cfg.genesis_timestamp = MassaTime::now(0) .unwrap() .saturating_sub(cfg.t0.checked_mul(1000).unwrap()); cfg.max_dependency_blocks = 10; @@ -540,7 +540,7 @@ async fn test_dep_in_back_order_with_max_dependency_blocks() { staking_file.path(), ); cfg.t0 = 1000.into(); - cfg.genesis_timestamp = UTime::now(0) + cfg.genesis_timestamp = MassaTime::now(0) .unwrap() .saturating_sub(cfg.t0.checked_mul(1000).unwrap()); cfg.max_dependency_blocks = 2; @@ -674,7 +674,7 @@ async fn test_add_block_that_depends_on_invalid_block() { staking_file.path(), ); cfg.t0 = 1000.into(); - cfg.genesis_timestamp = UTime::now(0) + cfg.genesis_timestamp = MassaTime::now(0) .unwrap() .saturating_sub(cfg.t0.checked_mul(1000).unwrap()); cfg.max_dependency_blocks = 7; diff --git a/massa-consensus/src/tests/scenarios91_1.rs b/massa-consensus/src/tests/scenarios91_1.rs index 1e2e5162a1c..f9cb99f3674 100644 --- a/massa-consensus/src/tests/scenarios91_1.rs +++ b/massa-consensus/src/tests/scenarios91_1.rs @@ -6,11 +6,11 @@ use crate::tests::tools::{self, generate_ledger_file}; use massa_hash::hash::Hash; use massa_models::{BlockId, Slot}; use massa_signature::{generate_random_private_key, PrivateKey}; -use massa_time::UTime; +use massa_time::MassaTime; use serial_test::serial; use std::collections::HashMap; -//use time::UTime; +//use time::MassaTime; #[tokio::test] #[serial] @@ -33,7 +33,7 @@ async fn test_ti() { cfg.t0 = 32000.into(); cfg.delta_f0 = 32; // to avoid timing pb for block in the future - cfg.genesis_timestamp = UTime::now(0) + cfg.genesis_timestamp = MassaTime::now(0) .unwrap() .saturating_sub(cfg.t0.checked_mul(1000).unwrap()); @@ -190,7 +190,7 @@ async fn test_gpi() { cfg.delta_f0 = 32; // to avoid timing problems for blocks in the future - cfg.genesis_timestamp = UTime::now(0) + cfg.genesis_timestamp = MassaTime::now(0) .unwrap() .saturating_sub(cfg.t0.checked_mul(1000).unwrap()); @@ -357,7 +357,7 @@ async fn test_old_stale() { cfg.delta_f0 = 32; // to avoid timing problems for blocks in the future - cfg.genesis_timestamp = UTime::now(0) + cfg.genesis_timestamp = MassaTime::now(0) .unwrap() .saturating_sub(cfg.t0.checked_mul(1000).unwrap()); diff --git a/massa-consensus/src/tests/scenarios91_2.rs b/massa-consensus/src/tests/scenarios91_2.rs index f487a93968c..1f9031d6c08 100644 --- a/massa-consensus/src/tests/scenarios91_2.rs +++ b/massa-consensus/src/tests/scenarios91_2.rs @@ -4,7 +4,7 @@ use crate::tests::tools::{self, generate_ledger_file}; use massa_hash::hash::Hash; use massa_models::Slot; use massa_signature::{generate_random_private_key, PrivateKey}; -use massa_time::UTime; +use massa_time::MassaTime; use serial_test::serial; use std::collections::HashMap; @@ -31,7 +31,7 @@ async fn test_queueing() { cfg.delta_f0 = 32; // to avoid timing problems for block in the future - cfg.genesis_timestamp = UTime::now(0) + cfg.genesis_timestamp = MassaTime::now(0) .unwrap() .saturating_sub(cfg.t0.checked_mul(1000).unwrap()); @@ -172,7 +172,7 @@ async fn test_doubles() { cfg.delta_f0 = 32; // to avoid timing pb for block in the future - cfg.genesis_timestamp = UTime::now(0) + cfg.genesis_timestamp = MassaTime::now(0) .unwrap() .saturating_sub(cfg.t0.checked_mul(1000).unwrap()); @@ -288,7 +288,7 @@ async fn test_double_staking() { cfg.delta_f0 = 32; // to avoid timing pb for block in the future - cfg.genesis_timestamp = UTime::now(0) + cfg.genesis_timestamp = MassaTime::now(0) .unwrap() .saturating_sub(cfg.t0.checked_mul(1000).unwrap()); @@ -415,7 +415,7 @@ async fn test_test_parents() { cfg.delta_f0 = 32; // to avoid timing pb for block in the future - cfg.genesis_timestamp = UTime::now(0) + cfg.genesis_timestamp = MassaTime::now(0) .unwrap() .saturating_sub(cfg.t0.checked_mul(1000).unwrap()); diff --git a/massa-consensus/src/tests/scenarios_endorsements.rs b/massa-consensus/src/tests/scenarios_endorsements.rs index 364b13e61a1..5d8d15bb92d 100644 --- a/massa-consensus/src/tests/scenarios_endorsements.rs +++ b/massa-consensus/src/tests/scenarios_endorsements.rs @@ -5,7 +5,7 @@ use massa_models::{ Address, Amount, BlockId, Endorsement, EndorsementContent, SerializeCompact, Slot, }; use massa_signature::{derive_public_key, generate_random_private_key, sign}; -use massa_time::UTime; +use massa_time::MassaTime; use serial_test::serial; use std::collections::HashMap; use std::str::FromStr; @@ -66,7 +66,7 @@ async fn test_endorsement_check() { cfg.block_reward = Amount::default(); cfg.roll_price = Amount::from_str("1000").unwrap(); cfg.operation_validity_periods = 100; - cfg.genesis_timestamp = UTime::now(0).unwrap().saturating_add(300.into()); + cfg.genesis_timestamp = MassaTime::now(0).unwrap().saturating_add(300.into()); cfg.endorsement_count = 1; tools::consensus_without_pool_test( diff --git a/massa-consensus/src/tests/scenarios_get_operations.rs b/massa-consensus/src/tests/scenarios_get_operations.rs index 1ed7e08402e..7d6770725a1 100644 --- a/massa-consensus/src/tests/scenarios_get_operations.rs +++ b/massa-consensus/src/tests/scenarios_get_operations.rs @@ -10,7 +10,7 @@ use massa_models::{ Address, Amount, BlockId, Operation, OperationSearchResult, OperationSearchResultStatus, Slot, }; use massa_signature::{derive_public_key, generate_random_private_key, PrivateKey, PublicKey}; -use massa_time::UTime; +use massa_time::MassaTime; use serial_test::serial; use std::collections::HashMap; use std::str::FromStr; @@ -94,7 +94,7 @@ async fn test_get_operation() { ); // there is only one node so it should be drawn at every slot - cfg.genesis_timestamp = UTime::now(0) + cfg.genesis_timestamp = MassaTime::now(0) .unwrap() .saturating_sub(cfg.t0.checked_mul(4).unwrap()) .saturating_add(300.into()); diff --git a/massa-consensus/src/tests/scenarios_get_selection_draws.rs b/massa-consensus/src/tests/scenarios_get_selection_draws.rs index 02c7f59e412..3d6697ffa39 100644 --- a/massa-consensus/src/tests/scenarios_get_selection_draws.rs +++ b/massa-consensus/src/tests/scenarios_get_selection_draws.rs @@ -4,7 +4,7 @@ use crate::tests::tools::{self, generate_ledger_file}; use massa_models::ledger::LedgerData; use massa_models::{Address, Amount, Slot}; use massa_signature::{derive_public_key, generate_random_private_key}; -use massa_time::UTime; +use massa_time::MassaTime; use serial_test::serial; use std::collections::HashMap; use std::str::FromStr; @@ -68,7 +68,7 @@ async fn test_get_selection_draws_high_end_slot() { cfg.block_reward = Amount::default(); cfg.roll_price = Amount::from_str("1000").unwrap(); cfg.operation_validity_periods = 100; - cfg.genesis_timestamp = UTime::now(0).unwrap().saturating_add(300.into()); + cfg.genesis_timestamp = MassaTime::now(0).unwrap().saturating_add(300.into()); tools::consensus_without_pool_test( cfg.clone(), diff --git a/massa-consensus/src/tests/scenarios_ledger.rs b/massa-consensus/src/tests/scenarios_ledger.rs index 80c1d59b1d9..f31ee1d9d68 100644 --- a/massa-consensus/src/tests/scenarios_ledger.rs +++ b/massa-consensus/src/tests/scenarios_ledger.rs @@ -15,7 +15,7 @@ use massa_models::ledger::LedgerChange; use massa_models::ledger::LedgerData; use massa_models::{Address, Amount, Slot}; use massa_signature::{derive_public_key, generate_random_private_key, PrivateKey}; -use massa_time::UTime; +use massa_time::MassaTime; use serial_test::serial; use std::collections::HashMap; use std::str::FromStr; @@ -645,7 +645,7 @@ async fn test_ledger_update_when_a_batch_of_blocks_becomes_final() { staking_file.path(), ); cfg.t0 = 1000.into(); - cfg.genesis_timestamp = UTime::now(0) + cfg.genesis_timestamp = MassaTime::now(0) .unwrap() .saturating_sub(cfg.t0.checked_mul(10).unwrap()); cfg.delta_f0 = 4; diff --git a/massa-consensus/src/tests/scenarios_pool_commands.rs b/massa-consensus/src/tests/scenarios_pool_commands.rs index 50346a1657a..c76853900f9 100644 --- a/massa-consensus/src/tests/scenarios_pool_commands.rs +++ b/massa-consensus/src/tests/scenarios_pool_commands.rs @@ -9,7 +9,7 @@ use massa_models::ledger::LedgerData; use massa_models::{Address, Amount, BlockId, Operation, Slot}; use massa_pool::PoolCommand; use massa_signature::{derive_public_key, generate_random_private_key, PrivateKey, PublicKey}; -use massa_time::UTime; +use massa_time::MassaTime; use serial_test::serial; use std::collections::HashMap; use std::str::FromStr; @@ -28,7 +28,7 @@ async fn test_update_current_slot_cmd_notification() { ); cfg.t0 = 1000.into(); cfg.thread_count = 1; - cfg.genesis_timestamp = UTime::now(0).unwrap().checked_add(1000.into()).unwrap(); + cfg.genesis_timestamp = MassaTime::now(0).unwrap().checked_add(1000.into()).unwrap(); let timeout = 150; @@ -42,7 +42,7 @@ async fn test_update_current_slot_cmd_notification() { consensus_event_receiver| { let slot_notification_filter = |cmd| match cmd { massa_pool::PoolCommand::UpdateCurrentSlot(slot) => { - Some((slot, UTime::now(0).unwrap())) + Some((slot, MassaTime::now(0).unwrap())) } _ => None, }; @@ -54,9 +54,13 @@ async fn test_update_current_slot_cmd_notification() { { assert_eq!(slot_cmd, Slot::new(0, 0)); if rec_time > cfg.genesis_timestamp { - assert!(rec_time.saturating_sub(cfg.genesis_timestamp) < UTime::from(timeout)) + assert!( + rec_time.saturating_sub(cfg.genesis_timestamp) < MassaTime::from(timeout) + ) } else { - assert!(cfg.genesis_timestamp.saturating_sub(rec_time) < UTime::from(timeout)) + assert!( + cfg.genesis_timestamp.saturating_sub(rec_time) < MassaTime::from(timeout) + ) } } @@ -69,14 +73,14 @@ async fn test_update_current_slot_cmd_notification() { if rec_time > cfg.genesis_timestamp { assert!( rec_time.saturating_sub(cfg.genesis_timestamp.saturating_add(cfg.t0)) - < UTime::from(timeout) + < MassaTime::from(timeout) ); } else { assert!( cfg.genesis_timestamp .saturating_add(cfg.t0) .saturating_sub(rec_time) - < UTime::from(timeout) + < MassaTime::from(timeout) ); } } @@ -104,7 +108,7 @@ async fn test_update_latest_final_block_cmd_notification() { staking_file.path(), ); cfg.t0 = 1000.into(); - cfg.genesis_timestamp = UTime::now(0).unwrap().checked_sub(100.into()).unwrap(); + cfg.genesis_timestamp = MassaTime::now(0).unwrap().checked_sub(100.into()).unwrap(); cfg.delta_f0 = 2; cfg.disable_block_creation = false; @@ -167,7 +171,7 @@ async fn test_new_final_ops() { staking_file.path(), ); cfg.t0 = 1000.into(); - cfg.genesis_timestamp = UTime::now(0).unwrap().checked_sub(cfg.t0).unwrap(); + cfg.genesis_timestamp = MassaTime::now(0).unwrap().checked_sub(cfg.t0).unwrap(); cfg.delta_f0 = 2; cfg.disable_block_creation = true; @@ -282,7 +286,7 @@ async fn test_max_attempts_get_operations() { staking_file.path(), ); cfg.t0 = 1000.into(); - cfg.genesis_timestamp = UTime::now(0).unwrap().checked_sub(cfg.t0).unwrap(); + cfg.genesis_timestamp = MassaTime::now(0).unwrap().checked_sub(cfg.t0).unwrap(); cfg.delta_f0 = 2; cfg.disable_block_creation = false; @@ -404,7 +408,7 @@ async fn test_max_batch_size_get_operations() { staking_file.path(), ); cfg.t0 = 1000.into(); - cfg.genesis_timestamp = UTime::now(0).unwrap().checked_sub(cfg.t0).unwrap(); + cfg.genesis_timestamp = MassaTime::now(0).unwrap().checked_sub(cfg.t0).unwrap(); cfg.delta_f0 = 2; cfg.disable_block_creation = false; diff --git a/massa-consensus/src/tests/tools.rs b/massa-consensus/src/tests/tools.rs index 3823d887966..4f4210606a0 100644 --- a/massa-consensus/src/tests/tools.rs +++ b/massa-consensus/src/tests/tools.rs @@ -26,7 +26,7 @@ use massa_protocol_exports::ProtocolCommand; use massa_signature::{ derive_public_key, generate_random_private_key, sign, PrivateKey, PublicKey, Signature, }; -use massa_time::UTime; +use massa_time::MassaTime; use num::rational::Ratio; use std::str::FromStr; use std::{ @@ -315,7 +315,7 @@ pub fn create_roll_transaction( pub async fn wait_pool_slot( pool_controller: &mut MockPoolController, - t0: UTime, + t0: MassaTime, period: u64, thread: u8, ) -> Slot { @@ -472,13 +472,12 @@ pub fn get_export_active_test_block( header: BlockHeader { content: BlockHeaderContent{ creator, - operation_merkle_root: Hash::from(&operations.iter().map(|op|{ + operation_merkle_root: Hash::from(&operations.iter().flat_map(|op|{ op .get_operation_id() .unwrap() .to_bytes() }) - .flatten() .collect::>()[..]), parents: parents.iter() .map(|(id,_)| *id) @@ -640,7 +639,7 @@ pub fn default_consensus_config( }); ConsensusConfig { - genesis_timestamp: UTime::now(0).unwrap(), + genesis_timestamp: MassaTime::now(0).unwrap(), thread_count, t0: 32000.into(), genesis_key, diff --git a/massa-models/src/api.rs b/massa-models/src/api.rs index 08d3c4d7814..86d0bd47152 100644 --- a/massa-models/src/api.rs +++ b/massa-models/src/api.rs @@ -8,7 +8,7 @@ use crate::{ Address, Amount, Block, BlockHashSet, BlockId, Config, Endorsement, EndorsementHashSet, EndorsementId, Operation, OperationHashSet, OperationId, Slot, Version, }; -use massa_time::UTime; +use massa_time::MassaTime; use serde::{Deserialize, Serialize}; use std::collections::{HashMap, HashSet}; use std::net::{IpAddr, SocketAddr}; @@ -18,7 +18,7 @@ pub struct NodeStatus { pub node_id: NodeId, pub node_ip: Option, pub version: Version, - pub current_time: UTime, + pub current_time: MassaTime, pub current_cycle: u64, pub connected_nodes: HashMap, pub last_slot: Option, @@ -355,8 +355,8 @@ fn display_if_true(value: bool, text: &str) -> String { #[derive(Debug, Deserialize, Clone, Copy, Serialize)] pub struct TimeInterval { - pub start: Option, - pub end: Option, + pub start: Option, + pub end: Option, } #[derive(Debug, Deserialize, Clone, Copy)] diff --git a/massa-models/src/ledger.rs b/massa-models/src/ledger.rs index e38e0b94240..2dcf4d59e39 100644 --- a/massa-models/src/ledger.rs +++ b/massa-models/src/ledger.rs @@ -4,19 +4,11 @@ use crate::{u8_from_slice, Amount, DeserializeCompact, ModelsError, SerializeCom use core::usize; use serde::{Deserialize, Serialize}; -#[derive(Debug, Serialize, Deserialize, Clone, Copy)] +#[derive(Debug, Default, Deserialize, Clone, Copy, Serialize)] pub struct LedgerData { pub balance: Amount, } -impl Default for LedgerData { - fn default() -> Self { - LedgerData { - balance: Amount::default(), - } - } -} - /// Checks performed: /// - Balance. impl SerializeCompact for LedgerData { @@ -47,17 +39,23 @@ impl LedgerData { pub fn apply_change(&mut self, change: &LedgerChange) -> Result<(), ModelsError> { if change.balance_increment { - self.balance = self.balance.checked_add(change.balance_delta).ok_or( - ModelsError::InvalidLedgerChange( - "balance overflow in LedgerData::apply_change".into(), - ), - )?; + self.balance = self + .balance + .checked_add(change.balance_delta) + .ok_or_else(|| { + ModelsError::InvalidLedgerChange( + "balance overflow in LedgerData::apply_change".into(), + ) + })?; } else { - self.balance = self.balance.checked_sub(change.balance_delta).ok_or( - ModelsError::InvalidLedgerChange( - "balance underflow in LedgerData::apply_change".into(), - ), - )?; + self.balance = self + .balance + .checked_sub(change.balance_delta) + .ok_or_else(|| { + ModelsError::InvalidLedgerChange( + "balance overflow in LedgerData::apply_change".into(), + ) + })?; } Ok(()) } @@ -90,18 +88,27 @@ impl LedgerChange { /// Applies another ledger change on top of self pub fn chain(&mut self, change: &LedgerChange) -> Result<(), ModelsError> { if self.balance_increment == change.balance_increment { - self.balance_delta = self.balance_delta.checked_add(change.balance_delta).ok_or( - ModelsError::InvalidLedgerChange("overflow in LedgerChange::chain".into()), - )?; + self.balance_delta = self + .balance_delta + .checked_add(change.balance_delta) + .ok_or_else(|| { + ModelsError::InvalidLedgerChange("overflow in LedgerChange::chain".into()) + })?; } else if change.balance_delta > self.balance_delta { - self.balance_delta = change.balance_delta.checked_sub(self.balance_delta).ok_or( - ModelsError::InvalidLedgerChange("underflow in LedgerChange::chain".into()), - )?; + self.balance_delta = change + .balance_delta + .checked_sub(self.balance_delta) + .ok_or_else(|| { + ModelsError::InvalidLedgerChange("underflow in LedgerChange::chain".into()) + })?; self.balance_increment = !self.balance_increment; } else { - self.balance_delta = self.balance_delta.checked_sub(change.balance_delta).ok_or( - ModelsError::InvalidLedgerChange("underflow in LedgerChange::chain".into()), - )?; + self.balance_delta = self + .balance_delta + .checked_sub(change.balance_delta) + .ok_or_else(|| { + ModelsError::InvalidLedgerChange("underflow in LedgerChange::chain".into()) + })?; } if self.balance_delta == Amount::default() { self.balance_increment = true; diff --git a/massa-models/src/serialization.rs b/massa-models/src/serialization.rs index 569d026dca2..0bec1c3dc96 100644 --- a/massa-models/src/serialization.rs +++ b/massa-models/src/serialization.rs @@ -3,7 +3,7 @@ use crate::error::ModelsError; use crate::Amount; use integer_encoding::VarInt; -use massa_time::UTime; +use massa_time::MassaTime; use std::convert::TryInto; use std::net::IpAddr; @@ -230,7 +230,7 @@ impl DeserializeCompact for IpAddr { } } -impl SerializeCompact for UTime { +impl SerializeCompact for MassaTime { fn to_bytes_compact(&self) -> Result, ModelsError> { Ok(self.to_millis().to_varint_bytes()) } @@ -238,7 +238,7 @@ impl SerializeCompact for UTime { /// Checks performed: /// - Buffer contains a valid u64. -impl DeserializeCompact for UTime { +impl DeserializeCompact for MassaTime { fn from_bytes_compact(buffer: &[u8]) -> Result<(Self, usize), ModelsError> { let (res_u64, delta) = u64::from_varint_bytes(buffer)?; Ok((res_u64.into(), delta)) diff --git a/massa-models/src/settings.rs b/massa-models/src/settings.rs index 117b98c3862..2d52285058d 100644 --- a/massa-models/src/settings.rs +++ b/massa-models/src/settings.rs @@ -2,7 +2,7 @@ use crate::Amount; use massa_hash::HASH_SIZE_BYTES; -use massa_time::UTime; +use massa_time::MassaTime; use serde::{Deserialize, Serialize}; pub const ADDRESS_SIZE_BYTES: usize = HASH_SIZE_BYTES; @@ -22,13 +22,13 @@ pub const SLOT_KEY_SIZE: usize = 9; #[derive(Debug, Deserialize, Serialize, Clone, Copy)] pub struct Config { /// Time in millis when the blockclique started. - pub genesis_timestamp: UTime, + pub genesis_timestamp: MassaTime, /// TESTNET: time when the blockclique is ended. - pub end_timestamp: Option, + pub end_timestamp: Option, /// Number of threads pub thread_count: u8, /// Time between the periods in the same thread. - pub t0: UTime, + pub t0: MassaTime, /// Threshold for fitness. pub delta_f0: u64, /// Maximum operation validity period count diff --git a/massa-models/src/stats.rs b/massa-models/src/stats.rs index fd2c05a8c05..a847209e33b 100644 --- a/massa-models/src/stats.rs +++ b/massa-models/src/stats.rs @@ -1,6 +1,6 @@ // Copyright (c) 2021 MASSA LABS -use massa_time::UTime; +use massa_time::MassaTime; use serde::{Deserialize, Serialize}; use std::fmt::Formatter; @@ -27,8 +27,8 @@ impl std::fmt::Display for NetworkStats { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ConsensusStats { - pub start_timespan: UTime, - pub end_timespan: UTime, + pub start_timespan: MassaTime, + pub end_timespan: MassaTime, pub final_block_count: u64, pub final_operation_count: u64, pub stale_block_count: u64, diff --git a/massa-models/src/timeslots.rs b/massa-models/src/timeslots.rs index 52221a178bc..b2d42f8e6b0 100644 --- a/massa-models/src/timeslots.rs +++ b/massa-models/src/timeslots.rs @@ -2,7 +2,7 @@ //! warning: assumes thread_count >= 1, t0_millis >= 1, t0_millis % thread_count == 0 -use massa_time::UTime; +use massa_time::MassaTime; use std::convert::TryInto; use crate::{ModelsError, Slot}; @@ -15,16 +15,16 @@ use crate::{ModelsError, Slot}; /// * slot: the considered slot. pub fn get_block_slot_timestamp( thread_count: u8, - t0: UTime, - genesis_timestamp: UTime, + t0: MassaTime, + genesis_timestamp: MassaTime, slot: Slot, -) -> Result { - let base: UTime = t0 +) -> Result { + let base: MassaTime = t0 .checked_div_u64(thread_count as u64) .or(Err(ModelsError::TimeOverflowError))? .checked_mul(slot.thread as u64) .or(Err(ModelsError::TimeOverflowError))?; - let shift: UTime = t0 + let shift: MassaTime = t0 .checked_mul(slot.period) .or(Err(ModelsError::TimeOverflowError))?; genesis_timestamp @@ -43,9 +43,9 @@ pub fn get_block_slot_timestamp( /// * timestamp: target timestamp in millis. pub fn get_latest_block_slot_at_timestamp( thread_count: u8, - t0: UTime, - genesis_timestamp: UTime, - timestamp: UTime, + t0: MassaTime, + genesis_timestamp: MassaTime, + timestamp: MassaTime, ) -> Result, ModelsError> { if let Ok(time_since_genesis) = timestamp.checked_sub(genesis_timestamp) { let thread: u8 = time_since_genesis @@ -68,19 +68,19 @@ pub fn get_latest_block_slot_at_timestamp( /// * genesis_timestamp: when the blockclique first started, in millis. pub fn get_current_latest_block_slot( thread_count: u8, - t0: UTime, - genesis_timestamp: UTime, + t0: MassaTime, + genesis_timestamp: MassaTime, clock_compensation: i64, ) -> Result, ModelsError> { get_latest_block_slot_at_timestamp( thread_count, t0, genesis_timestamp, - UTime::now(clock_compensation)?, + MassaTime::now(clock_compensation)?, ) } -/// Turns an UTime range [start, end) with optional start/end to a Slot range [start, end) with optional start/end +/// Turns an MassaTime range [start, end) with optional start/end to a Slot range [start, end) with optional start/end /// /// # Arguments /// * thread_count: number of threads. @@ -93,10 +93,10 @@ pub fn get_current_latest_block_slot( /// or ConsensusError on error pub fn time_range_to_slot_range( thread_count: u8, - t0: UTime, - genesis_timestamp: UTime, - start_time: Option, - end_time: Option, + t0: MassaTime, + genesis_timestamp: MassaTime, + start_time: Option, + end_time: Option, ) -> Result<(Option, Option), ModelsError> { let start_slot = match start_time { None => None, @@ -105,7 +105,7 @@ pub fn time_range_to_slot_range( let slot_number: u64 = t .saturating_sub(genesis_timestamp) .checked_add(inter_slot)? - .saturating_sub(UTime::EPSILON) + .saturating_sub(MassaTime::EPSILON) .checked_div_time(inter_slot)?; Some(Slot::new( slot_number @@ -127,7 +127,7 @@ pub fn time_range_to_slot_range( let slot_number: u64 = t .saturating_sub(genesis_timestamp) .checked_add(inter_slot)? - .saturating_sub(UTime::EPSILON) + .saturating_sub(MassaTime::EPSILON) .checked_div_time(inter_slot)?; Some(Slot::new( slot_number @@ -154,8 +154,8 @@ mod tests { #[serial] fn test_time_range_to_slot_range() { let thread_count = 3u8; - let t0: UTime = 30.into(); - let genesis_timestamp: UTime = 100.into(); + let t0: MassaTime = 30.into(); + let genesis_timestamp: MassaTime = 100.into(); /* slots: (0, 0) (0, 1) (0, 2) (1, 0) (1, 1) (1, 2) (2, 0) (2, 1) (2, 2) time: 100 110 120 130 140 150 160 170 180 */ diff --git a/massa-network/src/establisher.rs b/massa-network/src/establisher.rs index 46200b5ae23..4e08b3297c9 100644 --- a/massa-network/src/establisher.rs +++ b/massa-network/src/establisher.rs @@ -1,7 +1,7 @@ // Copyright (c) 2021 MASSA LABS #[cfg(not(test))] -use massa_time::UTime; +use massa_time::MassaTime; #[cfg(not(test))] use std::{io, net::SocketAddr}; #[cfg(not(test))] @@ -50,7 +50,7 @@ impl DefaultListener { /// Initiates a connection with given timeout in millis #[cfg(not(test))] #[derive(Debug)] -pub struct DefaultConnector(UTime); +pub struct DefaultConnector(MassaTime); #[cfg(not(test))] impl DefaultConnector { @@ -94,7 +94,10 @@ impl DefaultEstablisher { /// /// # Argument /// * timeout_duration: timeout duration in millis - pub async fn get_connector(&mut self, timeout_duration: UTime) -> io::Result { + pub async fn get_connector( + &mut self, + timeout_duration: MassaTime, + ) -> io::Result { Ok(DefaultConnector(timeout_duration)) } } diff --git a/massa-network/src/handshake_worker.rs b/massa-network/src/handshake_worker.rs index 8da55bce2f0..206a716de52 100644 --- a/massa-network/src/handshake_worker.rs +++ b/massa-network/src/handshake_worker.rs @@ -14,7 +14,7 @@ use massa_hash::hash::Hash; use massa_models::node::NodeId; use massa_models::Version; use massa_signature::{sign, verify_signature, PrivateKey}; -use massa_time::UTime; +use massa_time::MassaTime; use rand::{rngs::StdRng, RngCore, SeedableRng}; use tokio::time::timeout; @@ -32,7 +32,7 @@ pub struct HandshakeWorker { /// Our private key. private_key: PrivateKey, /// After timeout_duration millis, the handshake attempt is dropped. - timeout_duration: UTime, + timeout_duration: MassaTime, version: Version, } @@ -50,7 +50,7 @@ impl HandshakeWorker { socket_writer: WriteHalf, self_node_id: NodeId, private_key: PrivateKey, - timeout_duration: UTime, + timeout_duration: MassaTime, version: Version, ) -> HandshakeWorker { HandshakeWorker { diff --git a/massa-network/src/network_worker.rs b/massa-network/src/network_worker.rs index 6344e823219..c042cbe0b09 100644 --- a/massa-network/src/network_worker.rs +++ b/massa-network/src/network_worker.rs @@ -800,7 +800,7 @@ impl NetworkWorker { .active_connections .iter() .filter(|(_, (ip_addr, _))| &peer.ip == ip_addr) - .map(|(out_conn_id, (_, out_going))| { + .filter_map(|(out_conn_id, (_, out_going))| { self.active_nodes .iter() .filter_map(|(node_id, (conn_id, _))| { @@ -813,7 +813,6 @@ impl NetworkWorker { .next() .map(|node_id| (*node_id, *out_going)) }) - .flatten() .collect(), }, ) diff --git a/massa-network/src/node_worker.rs b/massa-network/src/node_worker.rs index 24474e93be9..6517d6a1e74 100644 --- a/massa-network/src/node_worker.rs +++ b/massa-network/src/node_worker.rs @@ -333,7 +333,7 @@ impl NodeWorker { // cut hash list on sub list if exceed max_ask_blocks_per_message massa_trace!("node_worker.run_loop. send Message::AskForBlocks", {"hashlist": list, "node": self.node_id}); for to_send_list in list.chunks(crate::settings::MAX_ASK_BLOCKS_PER_MESSAGE as usize) { - if self.try_send_to_node(&writer_command_tx, Message::AskForBlocks(to_send_list.iter().copied().collect())).is_err() { + if self.try_send_to_node(&writer_command_tx, Message::AskForBlocks(to_send_list.to_vec())).is_err() { break 'select_loop; } } diff --git a/massa-network/src/peer_info_database.rs b/massa-network/src/peer_info_database.rs index 40b8bc3014b..6fd0bcc4827 100644 --- a/massa-network/src/peer_info_database.rs +++ b/massa-network/src/peer_info_database.rs @@ -4,7 +4,7 @@ use crate::error::{NetworkConnectionErrorType, NetworkError}; use crate::settings::NetworkSettings; use itertools::Itertools; use massa_logging::massa_trace; -use massa_time::UTime; +use massa_time::MassaTime; use serde::{Deserialize, Serialize}; use serde_json::json; use serde_json::Value; @@ -26,9 +26,9 @@ pub struct PeerInfo { /// If peer is boostrap, ie peer was in initial peer file pub bootstrap: bool, /// Time in millis when peer was last alive - pub last_alive: Option, + pub last_alive: Option, /// Time in millis of peer's last failure - pub last_failure: Option, + pub last_failure: Option, /// Whether peer was promoted through another peer pub advertised: bool, @@ -78,7 +78,7 @@ pub struct PeerInfoDatabase { /// Total number of active in non-bootstrap connections pub active_in_nonbootstrap_connections: usize, /// Every wakeup_interval we try to establish a connection with known inactive peers - wakeup_interval: UTime, + wakeup_interval: MassaTime, /// Clock compensation. clock_compensation: i64, } @@ -127,7 +127,7 @@ fn cleanup_peers( peers: &mut HashMap, opt_new_peers: Option<&Vec>, clock_compensation: i64, - ban_timeout: UTime, + ban_timeout: MassaTime, ) -> Result<(), NetworkError> { // filter and map new peers, remove duplicates let mut res_new_peers: Vec = if let Some(new_peers) = opt_new_peers { @@ -206,7 +206,7 @@ fn cleanup_peers( // sort and truncate inactive banned peers // forget about old banned peers - let ban_limit = UTime::now(clock_compensation)?.saturating_sub(ban_timeout); + let ban_limit = MassaTime::now(clock_compensation)?.saturating_sub(ban_timeout); banned_peers.retain(|p| p.last_failure.map_or(false, |v| v >= ban_limit)); banned_peers.sort_unstable_by_key(|&p| (std::cmp::Reverse(p.last_failure), p.last_alive)); banned_peers.truncate(cfg.max_banned_peers); @@ -379,7 +379,7 @@ impl PeerInfoDatabase { let mut res_ips: Vec = Vec::new(); if available_slots_bootstrap > 0 { - let now = UTime::now(self.clock_compensation)?; + let now = MassaTime::now(self.clock_compensation)?; let mut sorted_peers: Vec = self .peers .values() @@ -396,7 +396,7 @@ impl PeerInfoDatabase { return now .saturating_sub(last_failure) .saturating_sub(self.wakeup_interval) - > UTime::from(0u64); + > MassaTime::from(0u64); } true }) @@ -413,7 +413,7 @@ impl PeerInfoDatabase { } if available_slots_nonbootstrap > 0 { - let now = UTime::now(self.clock_compensation)?; + let now = MassaTime::now(self.clock_compensation)?; let mut sorted_peers: Vec = self .peers .values() @@ -430,7 +430,7 @@ impl PeerInfoDatabase { return now .saturating_sub(last_failure) .saturating_sub(self.wakeup_interval) - > UTime::from(0u64); + > MassaTime::from(0u64); } true }) @@ -485,7 +485,7 @@ impl PeerInfoDatabase { } let (available_bootstrap_conns, available_nonbootstrap_conns) = self.get_available_out_connection_attempts(); - let peer = self.peers.get_mut(ip).ok_or_else(|| { + let peer = self.peers.get_mut(ip).ok_or({ NetworkError::PeerConnectionError(NetworkConnectionErrorType::PeerInfoNotFoundError( *ip, )) @@ -537,12 +537,12 @@ impl PeerInfoDatabase { pub fn peer_alive(&mut self, ip: &IpAddr) -> Result<(), NetworkError> { self.peers .get_mut(ip) - .ok_or_else(|| { + .ok_or({ NetworkError::PeerConnectionError( NetworkConnectionErrorType::PeerInfoNotFoundError(*ip), ) })? - .last_alive = Some(UTime::now(self.clock_compensation)?); + .last_alive = Some(MassaTime::now(self.clock_compensation)?); self.request_dump() } @@ -554,12 +554,12 @@ impl PeerInfoDatabase { pub fn peer_failed(&mut self, ip: &IpAddr) -> Result<(), NetworkError> { self.peers .get_mut(ip) - .ok_or_else(|| { + .ok_or({ NetworkError::PeerConnectionError( NetworkConnectionErrorType::PeerInfoNotFoundError(*ip), ) })? - .last_failure = Some(UTime::now(self.clock_compensation)?); + .last_failure = Some(MassaTime::now(self.clock_compensation)?); self.request_dump() } @@ -581,7 +581,7 @@ impl PeerInfoDatabase { active_out_connections: 0, active_in_connections: 0, }); - peer.last_failure = Some(UTime::now(self.clock_compensation)?); + peer.last_failure = Some(MassaTime::now(self.clock_compensation)?); if !peer.banned { peer.banned = true; if !peer.is_active() && !peer.bootstrap { @@ -605,7 +605,7 @@ impl PeerInfoDatabase { /// # Argument /// * ip : ip address of the considered peer. pub fn out_connection_closed(&mut self, ip: &IpAddr) -> Result<(), NetworkError> { - let peer = self.peers.get_mut(ip).ok_or_else(|| { + let peer = self.peers.get_mut(ip).ok_or({ NetworkError::PeerConnectionError(NetworkConnectionErrorType::PeerInfoNotFoundError( *ip, )) @@ -647,7 +647,7 @@ impl PeerInfoDatabase { /// # Argument /// * ip : ip address of the considered peer. pub fn in_connection_closed(&mut self, ip: &IpAddr) -> Result<(), NetworkError> { - let peer = self.peers.get_mut(ip).ok_or_else(|| { + let peer = self.peers.get_mut(ip).ok_or({ NetworkError::PeerConnectionError(NetworkConnectionErrorType::PeerInfoNotFoundError( *ip, )) @@ -695,7 +695,7 @@ impl PeerInfoDatabase { ) -> Result { // a connection attempt succeeded // remove out connection attempt and add out connection - let peer = self.peers.get_mut(ip).ok_or_else(|| { + let peer = self.peers.get_mut(ip).ok_or({ NetworkError::PeerConnectionError(NetworkConnectionErrorType::PeerInfoNotFoundError( *ip, )) @@ -726,7 +726,7 @@ impl PeerInfoDatabase { } peer.advertised = true; // we just connected to it. Assume advertised. if peer.banned { - peer.last_failure = Some(UTime::now(self.clock_compensation)?); + peer.last_failure = Some(MassaTime::now(self.clock_compensation)?); if !peer.is_active() && !peer.bootstrap { cleanup_peers( &self.network_settings, @@ -756,7 +756,7 @@ impl PeerInfoDatabase { /// # Argument /// * ip : ip address of the considered peer. pub fn out_connection_attempt_failed(&mut self, ip: &IpAddr) -> Result<(), NetworkError> { - let peer = self.peers.get_mut(ip).ok_or_else(|| { + let peer = self.peers.get_mut(ip).ok_or({ NetworkError::PeerConnectionError(NetworkConnectionErrorType::PeerInfoNotFoundError( *ip, )) @@ -775,7 +775,7 @@ impl PeerInfoDatabase { } else { self.active_out_nonbootstrap_connection_attempts -= 1; } - peer.last_failure = Some(UTime::now(self.clock_compensation)?); + peer.last_failure = Some(MassaTime::now(self.clock_compensation)?); if !peer.is_active() && !peer.bootstrap { cleanup_peers( &self.network_settings, @@ -823,7 +823,7 @@ impl PeerInfoDatabase { } if peer.banned { massa_trace!("in_connection_refused_peer_banned", {"ip": peer.ip}); - peer.last_failure = Some(UTime::now(self.clock_compensation)?); + peer.last_failure = Some(MassaTime::now(self.clock_compensation)?); self.request_dump()?; return Ok(false); } @@ -1356,7 +1356,8 @@ mod tests { default_peer_info_not_connected(IpAddr::V4(std::net::Ipv4Addr::new(169, 202, 0, 23))); banned_host1.bootstrap = true; banned_host1.banned = true; - banned_host1.last_alive = Some(UTime::now(0).unwrap().checked_sub(1000.into()).unwrap()); + banned_host1.last_alive = + Some(MassaTime::now(0).unwrap().checked_sub(1000.into()).unwrap()); peers.insert(banned_host1.ip, banned_host1); // peer not advertised, not return let mut connected_peers1 = @@ -1366,22 +1367,25 @@ mod tests { // peer Ok, return let mut connected_peers2 = default_peer_info_not_connected(IpAddr::V4(std::net::Ipv4Addr::new(169, 202, 0, 13))); - connected_peers2.last_alive = Some(UTime::now(0).unwrap().checked_sub(800.into()).unwrap()); + connected_peers2.last_alive = + Some(MassaTime::now(0).unwrap().checked_sub(800.into()).unwrap()); connected_peers2.last_failure = - Some(UTime::now(0).unwrap().checked_sub(1000.into()).unwrap()); + Some(MassaTime::now(0).unwrap().checked_sub(1000.into()).unwrap()); peers.insert(connected_peers2.ip, connected_peers2); // peer Ok, connected return let mut connected_peers1 = default_peer_info_not_connected(IpAddr::V4(std::net::Ipv4Addr::new(169, 202, 0, 17))); connected_peers1.active_out_connections = 1; - connected_peers1.last_alive = Some(UTime::now(0).unwrap().checked_sub(900.into()).unwrap()); + connected_peers1.last_alive = + Some(MassaTime::now(0).unwrap().checked_sub(900.into()).unwrap()); peers.insert(connected_peers1.ip, connected_peers1); // peer failure before alive but to early. return let mut connected_peers2 = default_peer_info_not_connected(IpAddr::V4(std::net::Ipv4Addr::new(169, 202, 0, 14))); - connected_peers2.last_alive = Some(UTime::now(0).unwrap().checked_sub(800.into()).unwrap()); + connected_peers2.last_alive = + Some(MassaTime::now(0).unwrap().checked_sub(800.into()).unwrap()); connected_peers2.last_failure = - Some(UTime::now(0).unwrap().checked_sub(2000.into()).unwrap()); + Some(MassaTime::now(0).unwrap().checked_sub(2000.into()).unwrap()); peers.insert(connected_peers2.ip, connected_peers2); let wakeup_interval = network_settings.wakeup_interval; @@ -1445,43 +1449,53 @@ mod tests { let mut connected_peers2 = default_peer_info_not_connected(IpAddr::V4(std::net::Ipv4Addr::new(169, 202, 0, 12))); connected_peers2.last_failure = - Some(UTime::now(0).unwrap().checked_sub(900.into()).unwrap()); + Some(MassaTime::now(0).unwrap().checked_sub(900.into()).unwrap()); peers.insert(connected_peers2.ip, connected_peers2); // peer failure before alive but to early. return let mut connected_peers2 = default_peer_info_not_connected(IpAddr::V4(std::net::Ipv4Addr::new(169, 202, 0, 13))); - connected_peers2.last_alive = Some(UTime::now(0).unwrap().checked_sub(900.into()).unwrap()); + connected_peers2.last_alive = + Some(MassaTime::now(0).unwrap().checked_sub(900.into()).unwrap()); connected_peers2.last_failure = - Some(UTime::now(0).unwrap().checked_sub(1000.into()).unwrap()); + Some(MassaTime::now(0).unwrap().checked_sub(1000.into()).unwrap()); peers.insert(connected_peers2.ip, connected_peers2); // peer alive no failure. return let mut connected_peers1 = default_peer_info_not_connected(IpAddr::V4(std::net::Ipv4Addr::new(169, 202, 0, 14))); connected_peers1.last_alive = - Some(UTime::now(0).unwrap().checked_sub(1000.into()).unwrap()); + Some(MassaTime::now(0).unwrap().checked_sub(1000.into()).unwrap()); peers.insert(connected_peers1.ip, connected_peers1); // peer banned not return. let mut banned_host1 = default_peer_info_not_connected(IpAddr::V4(std::net::Ipv4Addr::new(169, 202, 0, 23))); banned_host1.bootstrap = true; banned_host1.banned = true; - banned_host1.last_alive = Some(UTime::now(0).unwrap().checked_sub(1000.into()).unwrap()); + banned_host1.last_alive = + Some(MassaTime::now(0).unwrap().checked_sub(1000.into()).unwrap()); peers.insert(banned_host1.ip, banned_host1); // peer failure after alive not to early. return let mut connected_peers2 = default_peer_info_not_connected(IpAddr::V4(std::net::Ipv4Addr::new(169, 202, 0, 15))); - connected_peers2.last_alive = - Some(UTime::now(0).unwrap().checked_sub(12000.into()).unwrap()); - connected_peers2.last_failure = - Some(UTime::now(0).unwrap().checked_sub(11000.into()).unwrap()); + connected_peers2.last_alive = Some( + MassaTime::now(0) + .unwrap() + .checked_sub(12000.into()) + .unwrap(), + ); + connected_peers2.last_failure = Some( + MassaTime::now(0) + .unwrap() + .checked_sub(11000.into()) + .unwrap(), + ); peers.insert(connected_peers2.ip, connected_peers2); // peer failure after alive to early. not return let mut connected_peers2 = default_peer_info_not_connected(IpAddr::V4(std::net::Ipv4Addr::new(169, 202, 0, 16))); connected_peers2.last_alive = - Some(UTime::now(0).unwrap().checked_sub(2000.into()).unwrap()); + Some(MassaTime::now(0).unwrap().checked_sub(2000.into()).unwrap()); connected_peers2.last_failure = - Some(UTime::now(0).unwrap().checked_sub(1000.into()).unwrap()); + Some(MassaTime::now(0).unwrap().checked_sub(1000.into()).unwrap()); peers.insert(connected_peers2.ip, connected_peers2); // peer Ok, connected, not return let mut connected_peers1 = @@ -1553,17 +1567,18 @@ mod tests { .unwrap(); assert!(peers.is_empty()); - let now = UTime::now(0).unwrap(); + let now = MassaTime::now(0).unwrap(); let mut connected_peers1 = default_peer_info_connected(IpAddr::V4(std::net::Ipv4Addr::new(169, 202, 0, 11))); connected_peers1.last_alive = - Some(UTime::now(0).unwrap().checked_sub(1000.into()).unwrap()); + Some(MassaTime::now(0).unwrap().checked_sub(1000.into()).unwrap()); peers.insert(connected_peers1.ip, connected_peers1); let mut connected_peers2 = default_peer_info_connected(IpAddr::V4(std::net::Ipv4Addr::new(169, 202, 0, 12))); - connected_peers2.last_alive = Some(UTime::now(0).unwrap().checked_sub(900.into()).unwrap()); + connected_peers2.last_alive = + Some(MassaTime::now(0).unwrap().checked_sub(900.into()).unwrap()); let same_connected_peer = connected_peers2; let non_global = @@ -1598,7 +1613,7 @@ mod tests { advertised_host1.advertised = true; advertised_host1.active_out_connections = 0; advertised_host1.last_alive = - Some(UTime::now(0).unwrap().checked_sub(1000.into()).unwrap()); + Some(MassaTime::now(0).unwrap().checked_sub(1000.into()).unwrap()); let mut advertised_host2 = default_peer_info_connected(IpAddr::V4(std::net::Ipv4Addr::new(169, 202, 0, 36))); advertised_host2.bootstrap = false; @@ -1708,11 +1723,21 @@ mod tests { bootstrap: (ip[1] % 2) == 0, last_alive: match i % 4 { 0 => None, - _ => Some(UTime::now(0).unwrap().checked_sub(50000.into()).unwrap()), + _ => Some( + MassaTime::now(0) + .unwrap() + .checked_sub(50000.into()) + .unwrap(), + ), }, last_failure: match i % 5 { 0 => None, - _ => Some(UTime::now(0).unwrap().checked_sub(60000.into()).unwrap()), + _ => Some( + MassaTime::now(0) + .unwrap() + .checked_sub(60000.into()) + .unwrap(), + ), }, advertised: (ip[2] % 2) == 0, active_out_connection_attempts: 0, diff --git a/massa-network/src/settings.rs b/massa-network/src/settings.rs index 223fe01ff1f..782988875b3 100644 --- a/massa-network/src/settings.rs +++ b/massa-network/src/settings.rs @@ -1,6 +1,6 @@ // Copyright (c) 2021 MASSA LABS -use massa_time::UTime; +use massa_time::MassaTime; use serde::Deserialize; use std::net::{IpAddr, SocketAddr}; @@ -45,10 +45,10 @@ pub struct NetworkSettings { pub protocol_port: u16, /// Time interval spent waiting for a response from a peer. /// In millis - pub connect_timeout: UTime, + pub connect_timeout: MassaTime, /// Network_worker will try to connect to available peers every wakeup_interval. /// In millis - pub wakeup_interval: UTime, + pub wakeup_interval: MassaTime, /// Path to the file containing known peers. pub peers_file: std::path::PathBuf, /// Path to the file containing our private_key @@ -70,21 +70,21 @@ pub struct NetworkSettings { /// Limit on the number of banned peers we remember. pub max_banned_peers: usize, /// Peer database is dumped every peers_file_dump_interval in millis - pub peers_file_dump_interval: UTime, + pub peers_file_dump_interval: MassaTime, /// After message_timeout millis we are no longer waiting on handshake message - pub message_timeout: UTime, + pub message_timeout: MassaTime, /// Every ask_peer_list_interval in millis we ask every one for its advertisable peers list. - pub ask_peer_list_interval: UTime, + pub ask_peer_list_interval: MassaTime, /// Max wait time for sending a Network or Node event. - pub max_send_wait: UTime, + pub max_send_wait: MassaTime, /// Time after which we forget a node - pub ban_timeout: UTime, + pub ban_timeout: MassaTime, } #[cfg(test)] mod tests { use crate::NetworkSettings; - use massa_time::UTime; + use massa_time::MassaTime; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; impl Default for NetworkSettings { @@ -93,8 +93,8 @@ mod tests { bind: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080), routable_ip: Some(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1))), protocol_port: 0, - connect_timeout: UTime::from(180_000), - wakeup_interval: UTime::from(10_000), + connect_timeout: MassaTime::from(180_000), + wakeup_interval: MassaTime::from(10_000), peers_file: std::path::PathBuf::new(), target_bootstrap_connections: 1, max_out_bootstrap_connection_attempts: 1, @@ -104,12 +104,12 @@ mod tests { max_out_nonbootstrap_connection_attempts: 15, max_idle_peers: 3, max_banned_peers: 3, - peers_file_dump_interval: UTime::from(10_000), - message_timeout: UTime::from(5000u64), - ask_peer_list_interval: UTime::from(50000u64), + peers_file_dump_interval: MassaTime::from(10_000), + message_timeout: MassaTime::from(5000u64), + ask_peer_list_interval: MassaTime::from(50000u64), private_key_file: std::path::PathBuf::new(), - max_send_wait: UTime::from(100), - ban_timeout: UTime::from(100_000_000), + max_send_wait: MassaTime::from(100), + ban_timeout: MassaTime::from(100_000_000), } } } diff --git a/massa-network/src/tests/mock_establisher.rs b/massa-network/src/tests/mock_establisher.rs index f17bc1c0141..7e92a7dea68 100644 --- a/massa-network/src/tests/mock_establisher.rs +++ b/massa-network/src/tests/mock_establisher.rs @@ -1,6 +1,6 @@ // Copyright (c) 2021 MASSA LABS -use massa_time::UTime; +use massa_time::MassaTime; use std::io; use std::net::SocketAddr; use tokio::io::DuplexStream; @@ -66,7 +66,7 @@ impl MockListener { #[derive(Debug)] pub struct MockConnector { connection_connector_tx: mpsc::Sender<(ReadHalf, WriteHalf, SocketAddr, oneshot::Sender)>, - timeout_duration: UTime, + timeout_duration: MassaTime, } impl MockConnector { @@ -128,7 +128,7 @@ impl MockEstablisher { pub async fn get_connector( &mut self, - timeout_duration: UTime, + timeout_duration: MassaTime, ) -> std::io::Result { // create connector stream diff --git a/massa-network/src/tests/scenarios.rs b/massa-network/src/tests/scenarios.rs index d9f02c86530..d9e785612ae 100644 --- a/massa-network/src/tests/scenarios.rs +++ b/massa-network/src/tests/scenarios.rs @@ -12,7 +12,7 @@ use massa_hash::{self, hash::Hash}; use massa_models::node::NodeId; use massa_models::{BlockId, Endorsement, EndorsementContent, SerializeCompact, Slot}; use massa_signature::sign; -use massa_time::UTime; +use massa_time::MassaTime; use serial_test::serial; use std::collections::HashMap; use std::{ @@ -32,7 +32,7 @@ use tracing::trace; async fn test_node_worker_shutdown() { let bind_port: u16 = 50_000; let temp_peers_file = super::tools::generate_peers_file(&vec![]); - let network_conf = super::tools::create_network_config(bind_port, &temp_peers_file.path()); + let network_conf = super::tools::create_network_config(bind_port, temp_peers_file.path()); let (duplex_controller, _duplex_mock) = tokio::io::duplex(1); let (duplex_mock_read, duplex_mock_write) = tokio::io::split(duplex_controller); let reader = ReadBinder::new(duplex_mock_read); @@ -484,8 +484,8 @@ async fn test_advertised_and_wakeup_interval() { active_in_connections: 0, }]); let mut network_conf = super::tools::create_network_config(bind_port, temp_peers_file.path()); - network_conf.wakeup_interval = UTime::from(500); - network_conf.connect_timeout = UTime::from(2000); + network_conf.wakeup_interval = MassaTime::from(500); + network_conf.connect_timeout = MassaTime::from(2000); tools::network_test( network_conf.clone(), diff --git a/massa-network/src/tests/tools.rs b/massa-network/src/tests/tools.rs index fc1636c8cd5..1140f180ad1 100644 --- a/massa-network/src/tests/tools.rs +++ b/massa-network/src/tests/tools.rs @@ -13,7 +13,7 @@ use massa_models::{ Address, Amount, BlockId, Operation, OperationContent, OperationType, SerializeCompact, Version, }; use massa_signature::{derive_public_key, generate_random_private_key, sign}; -use massa_time::UTime; +use massa_time::MassaTime; use std::str::FromStr; use std::{ future::Future, @@ -81,10 +81,10 @@ pub fn create_network_config( .unwrap(), routable_ip: Some(BASE_NETWORK_CONTROLLER_IP), protocol_port: network_controller_port, - connect_timeout: UTime::from(3000), + connect_timeout: MassaTime::from(3000), peers_file: peers_file_path.to_path_buf(), target_out_nonbootstrap_connections: 10, - wakeup_interval: UTime::from(3000), + wakeup_interval: MassaTime::from(3000), target_bootstrap_connections: 0, max_out_bootstrap_connection_attempts: 1, max_in_nonbootstrap_connections: 100, @@ -92,12 +92,12 @@ pub fn create_network_config( max_out_nonbootstrap_connection_attempts: 100, max_idle_peers: 100, max_banned_peers: 100, - peers_file_dump_interval: UTime::from(30000), - message_timeout: UTime::from(5000u64), - ask_peer_list_interval: UTime::from(50000u64), + peers_file_dump_interval: MassaTime::from(30000), + message_timeout: MassaTime::from(5000u64), + ask_peer_list_interval: MassaTime::from(50000u64), private_key_file: get_temp_private_key_file().path().to_path_buf(), - max_send_wait: UTime::from(100), - ban_timeout: UTime::from(100_000_000), + max_send_wait: MassaTime::from(100), + ban_timeout: MassaTime::from(100_000_000), } } @@ -294,7 +294,7 @@ pub async fn full_connection_from_controller( pub async fn wait_network_event( network_event_receiver: &mut NetworkEventReceiver, - timeout: UTime, + timeout: MassaTime, filter_map: F, ) -> Option where diff --git a/massa-node/src/main.rs b/massa-node/src/main.rs index a7c535dc21f..6e88daf4146 100644 --- a/massa-node/src/main.rs +++ b/massa-node/src/main.rs @@ -21,8 +21,7 @@ use massa_network::{start_network_controller, Establisher, NetworkCommandSender, use massa_pool::{start_pool_controller, PoolCommandSender, PoolManager}; use massa_protocol_exports::ProtocolManager; use massa_protocol_worker::start_protocol_controller; -use massa_time::UTime; - +use massa_time::MassaTime; use std::process; use tokio::signal; use tokio::sync::mpsc; @@ -47,7 +46,7 @@ async fn launch() -> ( ) { info!("Node version : {}", *crate::settings::VERSION); if let Some(end) = *massa_consensus::settings::END_TIMESTAMP { - if UTime::now(0).expect("could not get now time") > end { + if MassaTime::now(0).expect("could not get now time") > end { panic!("This episode has come to an end, please get the latest testnet node version to continue"); } } diff --git a/massa-pool/src/operation_pool.rs b/massa-pool/src/operation_pool.rs index 4bc023fcf9f..8a505e2ef7b 100644 --- a/massa-pool/src/operation_pool.rs +++ b/massa-pool/src/operation_pool.rs @@ -325,9 +325,11 @@ impl OperationPool { .map(|op_id| { self.ops .get(op_id) - .ok_or(PoolError::ContainerInconsistency( - "op in ops by address is not in ops".to_string(), - )) + .ok_or_else(|| { + PoolError::ContainerInconsistency( + "op in ops by address is not in ops".to_string(), + ) + }) .map(|op| { ( *op_id, diff --git a/massa-pool/src/tests/mock_protocol_controller.rs b/massa-pool/src/tests/mock_protocol_controller.rs index 022c3b973b6..feb5a9eb030 100644 --- a/massa-pool/src/tests/mock_protocol_controller.rs +++ b/massa-pool/src/tests/mock_protocol_controller.rs @@ -4,7 +4,7 @@ use massa_models::{Endorsement, EndorsementHashMap, Operation, OperationHashMap} use massa_protocol_exports::{ ProtocolCommand, ProtocolCommandSender, ProtocolPoolEvent, ProtocolPoolEventReceiver, }; -use massa_time::UTime; +use massa_time::MassaTime; use tokio::{sync::mpsc, time::sleep}; const CHANNEL_SIZE: usize = 256; @@ -29,7 +29,7 @@ impl MockProtocolController { ) } - pub async fn wait_command(&mut self, timeout: UTime, filter_map: F) -> Option + pub async fn wait_command(&mut self, timeout: MassaTime, filter_map: F) -> Option where F: Fn(ProtocolCommand) -> Option, { diff --git a/massa-protocol-exports/src/settings.rs b/massa-protocol-exports/src/settings.rs index e8c579a2572..78dfc378cfd 100644 --- a/massa-protocol-exports/src/settings.rs +++ b/massa-protocol-exports/src/settings.rs @@ -1,6 +1,6 @@ // Copyright (c) 2021 MASSA LABS -use massa_time::UTime; +use massa_time::MassaTime; use serde::Deserialize; pub const CHANNEL_SIZE: usize = 256; @@ -8,12 +8,12 @@ pub const CHANNEL_SIZE: usize = 256; /// Protocol Configuration #[derive(Debug, Deserialize, Clone, Copy)] pub struct ProtocolSettings { - pub ask_block_timeout: UTime, + pub ask_block_timeout: MassaTime, pub max_node_known_blocks_size: usize, pub max_node_wanted_blocks_size: usize, pub max_known_ops_size: usize, pub max_known_endorsements_size: usize, pub max_simultaneous_ask_blocks_per_node: usize, /// Max wait time for sending a Network or Node event. - pub max_send_wait: UTime, + pub max_send_wait: MassaTime, } diff --git a/massa-protocol-exports/src/tests/mock_network_controller.rs b/massa-protocol-exports/src/tests/mock_network_controller.rs index 453dfa8c96b..a32f978fd4b 100644 --- a/massa-protocol-exports/src/tests/mock_network_controller.rs +++ b/massa-protocol-exports/src/tests/mock_network_controller.rs @@ -3,7 +3,7 @@ use massa_models::node::NodeId; use massa_models::{Block, BlockHeader, BlockId, Endorsement, Operation}; use massa_network::{NetworkCommand, NetworkCommandSender, NetworkEvent, NetworkEventReceiver}; -use massa_time::UTime; +use massa_time::MassaTime; use tokio::{sync::mpsc, time::sleep}; const CHANNEL_SIZE: usize = 256; @@ -28,7 +28,7 @@ impl MockNetworkController { ) } - pub async fn wait_command(&mut self, timeout: UTime, filter_map: F) -> Option + pub async fn wait_command(&mut self, timeout: MassaTime, filter_map: F) -> Option where F: Fn(NetworkCommand) -> Option, { diff --git a/massa-protocol-exports/src/tests/tools.rs b/massa-protocol-exports/src/tests/tools.rs index e71dde1f99a..e27f693815a 100644 --- a/massa-protocol-exports/src/tests/tools.rs +++ b/massa-protocol-exports/src/tests/tools.rs @@ -15,7 +15,7 @@ use massa_network::NetworkCommand; use massa_signature::{ derive_public_key, generate_random_private_key, sign, PrivateKey, PublicKey, }; -use massa_time::UTime; +use massa_time::MassaTime; use std::collections::HashMap; use tokio::time::sleep; @@ -234,7 +234,7 @@ pub fn create_protocol_settings() -> ProtocolSettings { max_node_known_blocks_size: 100, max_node_wanted_blocks_size: 100, max_simultaneous_ask_blocks_per_node: 10, - max_send_wait: UTime::from(100), + max_send_wait: MassaTime::from(100), max_known_ops_size: 1000, max_known_endorsements_size: 1000, } @@ -242,7 +242,7 @@ pub fn create_protocol_settings() -> ProtocolSettings { pub async fn wait_protocol_event( protocol_event_receiver: &mut ProtocolEventReceiver, - timeout: UTime, + timeout: MassaTime, filter_map: F, ) -> Option where @@ -263,7 +263,7 @@ where pub async fn wait_protocol_pool_event( protocol_event_receiver: &mut ProtocolPoolEventReceiver, - timeout: UTime, + timeout: MassaTime, filter_map: F, ) -> Option where @@ -327,7 +327,7 @@ pub async fn assert_banned_nodes( mut nodes: Vec, network_controller: &mut MockNetworkController, ) { - let timer = sleep(UTime::from(5000).into()); + let timer = sleep(MassaTime::from(5000).into()); tokio::pin!(timer); loop { tokio::select! { diff --git a/massa-protocol-worker/src/tests/ban_nodes_scenarios.rs b/massa-protocol-worker/src/tests/ban_nodes_scenarios.rs index 5d4e69d1478..1320b813a7b 100644 --- a/massa-protocol-worker/src/tests/ban_nodes_scenarios.rs +++ b/massa-protocol-worker/src/tests/ban_nodes_scenarios.rs @@ -462,7 +462,7 @@ async fn test_protocol_bans_all_nodes_propagating_an_attack_attempt() { assert_eq!(expected_hash, received_hash); } else { assert!( - !tools::wait_protocol_event( + tools::wait_protocol_event( &mut protocol_event_receiver, 150.into(), |evt| match evt { @@ -471,7 +471,7 @@ async fn test_protocol_bans_all_nodes_propagating_an_attack_attempt() { }, ) .await - .is_some(), + .is_none(), "caching was ignored" ); } diff --git a/massa-time/src/lib.rs b/massa-time/src/lib.rs index 2a1878027f2..72989a7286c 100644 --- a/massa-time/src/lib.rs +++ b/massa-time/src/lib.rs @@ -16,26 +16,26 @@ use serde::{Deserialize, Serialize}; /// Time structure used every where. /// Millis since 01/01/1970. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -pub struct UTime(u64); +pub struct MassaTime(u64); -impl fmt::Display for UTime { +impl fmt::Display for MassaTime { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.to_millis()) } } -impl From for UTime { +impl From for MassaTime { /// Conversion from u64, representing timestamp in millis. /// ``` /// # use massa_time::*; - /// let time : UTime = UTime::from(42); + /// let time : MassaTime = MassaTime::from(42); /// ``` fn from(value: u64) -> Self { - UTime(value) + MassaTime(value) } } -impl TryFrom for UTime { +impl TryFrom for MassaTime { type Error = TimeError; /// Conversion from `std::time::Duration`. @@ -44,11 +44,11 @@ impl TryFrom for UTime { /// # use massa_time::*; /// # use std::convert::TryFrom; /// let duration: Duration = Duration::from_millis(42); - /// let time : UTime = UTime::from(42); - /// assert_eq!(time, UTime::try_from(duration).unwrap()); + /// let time : MassaTime = MassaTime::from(42); + /// assert_eq!(time, MassaTime::try_from(duration).unwrap()); /// ``` fn try_from(value: Duration) -> Result { - Ok(UTime( + Ok(MassaTime( value .as_millis() .try_into() @@ -57,23 +57,23 @@ impl TryFrom for UTime { } } -impl From for Duration { - /// Conversion Utime to duration, representing timestamp in millis. +impl From for Duration { + /// Conversion massa_time to duration, representing timestamp in millis. /// ``` /// # use std::time::Duration; /// # use massa_time::*; /// # use std::convert::Into; /// let duration: Duration = Duration::from_millis(42); - /// let time : UTime = UTime::from(42); + /// let time : MassaTime = MassaTime::from(42); /// let res: Duration = time.into(); /// assert_eq!(res, duration); /// ``` - fn from(value: UTime) -> Self { + fn from(value: MassaTime) -> Self { value.to_duration() } } -impl FromStr for UTime { +impl FromStr for MassaTime { type Err = crate::TimeError; /// Conversion from `&str`. @@ -82,20 +82,20 @@ impl FromStr for UTime { /// # use massa_time::*; /// # use std::str::FromStr; /// let duration: &str = "42"; - /// let time : UTime = UTime::from(42); + /// let time : MassaTime = MassaTime::from(42); /// - /// assert_eq!(time, UTime::from_str(duration).unwrap()); + /// assert_eq!(time, MassaTime::from_str(duration).unwrap()); /// ``` fn from_str(s: &str) -> Result { - Ok(UTime( + Ok(MassaTime( u64::from_str(s).map_err(|_| Self::Err::ConversionError)?, )) } } -impl UTime { +impl MassaTime { /// Smallest time interval - pub const EPSILON: UTime = UTime(1); + pub const EPSILON: MassaTime = MassaTime(1); /// Gets current unix timestamp (resolution: milliseconds). /// @@ -108,9 +108,9 @@ impl UTime { /// # use std::convert::TryFrom; /// # use std::cmp::max; /// let now_duration : Duration = SystemTime::now().duration_since(UNIX_EPOCH).unwrap(); - /// let now_utime : UTime = UTime::now(0).unwrap(); - /// let converted :UTime = UTime::try_from(now_duration).unwrap(); - /// assert!(max(now_utime.saturating_sub(converted), converted.saturating_sub(now_utime)) < 100.into()) + /// let now_massa_time : MassaTime = MassaTime::now(0).unwrap(); + /// let converted :MassaTime = MassaTime::try_from(now_duration).unwrap(); + /// assert!(max(now_massa_time.saturating_sub(converted), converted.saturating_sub(now_massa_time)) < 100.into()) /// ``` pub fn now(compensation_millis: i64) -> Result { let now: i64 = SystemTime::now() @@ -124,7 +124,7 @@ impl UTime { .ok_or(TimeError::TimeOverflowError)? .try_into() .map_err(|_| TimeError::TimeOverflowError)?; - Ok(UTime(compensated)) + Ok(MassaTime(compensated)) } /// Conversion to `std::time::Duration`. @@ -132,7 +132,7 @@ impl UTime { /// # use std::time::Duration; /// # use massa_time::*; /// let duration: Duration = Duration::from_millis(42); - /// let time : UTime = UTime::from(42); + /// let time : MassaTime = MassaTime::from(42); /// let res: Duration = time.to_duration(); /// assert_eq!(res, duration); /// ``` @@ -143,7 +143,7 @@ impl UTime { /// Conversion to u64, representing millis. /// ``` /// # use massa_time::*; - /// let time : UTime = UTime::from(42); + /// let time : MassaTime = MassaTime::from(42); /// let res: u64 = time.to_millis(); /// assert_eq!(res, 42); /// ``` @@ -157,16 +157,16 @@ impl UTime { /// # use std::convert::TryFrom; /// # use std::cmp::max; /// # use tokio::time::Instant; - /// let (cur_timestamp, cur_instant): (UTime, Instant) = (UTime::now(0).unwrap(), Instant::now()); - /// let utime_instant: Instant = cur_timestamp.estimate_instant(0).unwrap(); + /// let (cur_timestamp, cur_instant): (MassaTime, Instant) = (MassaTime::now(0).unwrap(), Instant::now()); + /// let massa_time_instant: Instant = cur_timestamp.estimate_instant(0).unwrap(); /// assert!(max( - /// utime_instant.saturating_duration_since(cur_instant), - /// cur_instant.saturating_duration_since(utime_instant) + /// massa_time_instant.saturating_duration_since(cur_instant), + /// cur_instant.saturating_duration_since(massa_time_instant) /// ) < std::time::Duration::from_millis(10)) /// ``` pub fn estimate_instant(self, compensation_millis: i64) -> Result { - let (cur_timestamp, cur_instant): (UTime, Instant) = - (UTime::now(compensation_millis)?, Instant::now()); + let (cur_timestamp, cur_instant): (MassaTime, Instant) = + (MassaTime::now(compensation_millis)?, Instant::now()); cur_instant .checked_add(self.to_duration()) .ok_or(TimeError::TimeOverflowError)? @@ -176,62 +176,62 @@ impl UTime { /// ``` /// # use massa_time::*; - /// let time_1 : UTime = UTime::from(42); - /// let time_2 : UTime = UTime::from(7); - /// let res : UTime = time_1.saturating_sub(time_2); - /// assert_eq!(res, UTime::from(42-7)) + /// let time_1 : MassaTime = MassaTime::from(42); + /// let time_2 : MassaTime = MassaTime::from(7); + /// let res : MassaTime = time_1.saturating_sub(time_2); + /// assert_eq!(res, MassaTime::from(42-7)) /// ``` - pub fn saturating_sub(self, t: UTime) -> Self { - UTime(self.0.saturating_sub(t.0)) + pub fn saturating_sub(self, t: MassaTime) -> Self { + MassaTime(self.0.saturating_sub(t.0)) } /// ``` /// # use massa_time::*; - /// let time_1 : UTime = UTime::from(42); - /// let time_2 : UTime = UTime::from(7); - /// let res : UTime = time_1.saturating_add(time_2); - /// assert_eq!(res, UTime::from(42+7)) + /// let time_1 : MassaTime = MassaTime::from(42); + /// let time_2 : MassaTime = MassaTime::from(7); + /// let res : MassaTime = time_1.saturating_add(time_2); + /// assert_eq!(res, MassaTime::from(42+7)) /// ``` - pub fn saturating_add(self, t: UTime) -> Self { - UTime(self.0.saturating_add(t.0)) + pub fn saturating_add(self, t: MassaTime) -> Self { + MassaTime(self.0.saturating_add(t.0)) } /// ``` /// # use massa_time::*; - /// let time_1 : UTime = UTime::from(42); - /// let time_2 : UTime = UTime::from(7); - /// let res : UTime = time_1.checked_sub(time_2).unwrap(); - /// assert_eq!(res, UTime::from(42-7)) + /// let time_1 : MassaTime = MassaTime::from(42); + /// let time_2 : MassaTime = MassaTime::from(7); + /// let res : MassaTime = time_1.checked_sub(time_2).unwrap(); + /// assert_eq!(res, MassaTime::from(42-7)) /// ``` - pub fn checked_sub(self, t: UTime) -> Result { + pub fn checked_sub(self, t: MassaTime) -> Result { self.0 .checked_sub(t.0) .ok_or_else(|| TimeError::CheckedOperationError("subtraction error".to_string())) - .map(UTime) + .map(MassaTime) } /// ``` /// # use massa_time::*; - /// let time_1 : UTime = UTime::from(42); - /// let time_2 : UTime = UTime::from(7); - /// let res : UTime = time_1.checked_add(time_2).unwrap(); - /// assert_eq!(res, UTime::from(42+7)) + /// let time_1 : MassaTime = MassaTime::from(42); + /// let time_2 : MassaTime = MassaTime::from(7); + /// let res : MassaTime = time_1.checked_add(time_2).unwrap(); + /// assert_eq!(res, MassaTime::from(42+7)) /// ``` - pub fn checked_add(self, t: UTime) -> Result { + pub fn checked_add(self, t: MassaTime) -> Result { self.0 .checked_add(t.0) .ok_or_else(|| TimeError::CheckedOperationError("addition error".to_string())) - .map(UTime) + .map(MassaTime) } /// ``` /// # use massa_time::*; - /// let time_1 : UTime = UTime::from(42); - /// let time_2 : UTime = UTime::from(7); + /// let time_1 : MassaTime = MassaTime::from(42); + /// let time_2 : MassaTime = MassaTime::from(7); /// let res : u64 = time_1.checked_div_time(time_2).unwrap(); /// assert_eq!(res,42/7) /// ``` - pub fn checked_div_time(self, t: UTime) -> Result { + pub fn checked_div_time(self, t: MassaTime) -> Result { self.0 .checked_div(t.0) .ok_or_else(|| TimeError::CheckedOperationError("division error".to_string())) @@ -239,61 +239,61 @@ impl UTime { /// ``` /// # use massa_time::*; - /// let time_1 : UTime = UTime::from(42); - /// let res : UTime = time_1.checked_div_u64(7).unwrap(); - /// assert_eq!(res,UTime::from(42/7)) + /// let time_1 : MassaTime = MassaTime::from(42); + /// let res : MassaTime = time_1.checked_div_u64(7).unwrap(); + /// assert_eq!(res,MassaTime::from(42/7)) /// ``` - pub fn checked_div_u64(self, n: u64) -> Result { + pub fn checked_div_u64(self, n: u64) -> Result { self.0 .checked_div(n) .ok_or_else(|| TimeError::CheckedOperationError("division error".to_string())) - .map(UTime) + .map(MassaTime) } /// ``` /// # use massa_time::*; - /// let time_1 : UTime = UTime::from(42); - /// let res : UTime = time_1.checked_mul(7).unwrap(); - /// assert_eq!(res,UTime::from(42*7)) + /// let time_1 : MassaTime = MassaTime::from(42); + /// let res : MassaTime = time_1.checked_mul(7).unwrap(); + /// assert_eq!(res,MassaTime::from(42*7)) /// ``` pub fn checked_mul(self, n: u64) -> Result { self.0 .checked_mul(n) .ok_or_else(|| TimeError::CheckedOperationError("multiplication error".to_string())) - .map(UTime) + .map(MassaTime) } /// ``` /// # use massa_time::*; - /// let time_1 : UTime = UTime::from(42); - /// let time_2 : UTime = UTime::from(7); - /// let res : UTime = time_1.checked_rem_time(time_2).unwrap(); - /// assert_eq!(res,UTime::from(42%7)) + /// let time_1 : MassaTime = MassaTime::from(42); + /// let time_2 : MassaTime = MassaTime::from(7); + /// let res : MassaTime = time_1.checked_rem_time(time_2).unwrap(); + /// assert_eq!(res,MassaTime::from(42%7)) /// ``` - pub fn checked_rem_time(self, t: UTime) -> Result { + pub fn checked_rem_time(self, t: MassaTime) -> Result { self.0 .checked_rem(t.0) .ok_or_else(|| TimeError::CheckedOperationError("remainder error".to_string())) - .map(UTime) + .map(MassaTime) } /// ``` /// # use massa_time::*; - /// let time_1 : UTime = UTime::from(42); - /// let res : UTime = time_1.checked_rem_u64(7).unwrap(); - /// assert_eq!(res,UTime::from(42%7)) + /// let time_1 : MassaTime = MassaTime::from(42); + /// let res : MassaTime = time_1.checked_rem_u64(7).unwrap(); + /// assert_eq!(res,MassaTime::from(42%7)) /// ``` pub fn checked_rem_u64(self, n: u64) -> Result { self.0 .checked_rem(n) .ok_or_else(|| TimeError::CheckedOperationError("remainder error".to_string())) - .map(UTime) + .map(MassaTime) } /// ``` /// # use massa_time::*; - /// let utime : UTime = UTime::from(0); - /// assert_eq!(utime.to_utc_string(), "1970-01-01 00:00:00 UTC") + /// let massa_time : MassaTime = MassaTime::from(0); + /// assert_eq!(massa_time.to_utc_string(), "1970-01-01 00:00:00 UTC") /// ``` pub fn to_utc_string(self) -> String { let naive = NaiveDateTime::from_timestamp( @@ -306,8 +306,8 @@ impl UTime { /// ``` /// # use massa_time::*; - /// let utime = UTime::from(1000 * ( 8 * 24*60*60 + 1 * 60*60 + 3 * 60 + 6 )); - /// let (days, hours, mins, secs) = utime.days_hours_mins_secs().unwrap(); + /// let massa_time = MassaTime::from(1000 * ( 8 * 24*60*60 + 1 * 60*60 + 3 * 60 + 6 )); + /// let (days, hours, mins, secs) = massa_time.days_hours_mins_secs().unwrap(); /// assert_eq!(days, 8); /// assert_eq!(hours, 1); /// assert_eq!(mins, 3); diff --git a/massa-wallet/src/lib.rs b/massa-wallet/src/lib.rs index c0a266f976c..c57bc01a6e5 100644 --- a/massa-wallet/src/lib.rs +++ b/massa-wallet/src/lib.rs @@ -9,7 +9,7 @@ use massa_models::Operation; use massa_models::OperationContent; use massa_models::SerializeCompact; use massa_signature::{derive_public_key, sign, PrivateKey, PublicKey}; -use massa_time::UTime; +use massa_time::MassaTime; use serde::{Deserialize, Serialize}; use std::path::PathBuf; @@ -143,9 +143,9 @@ impl std::fmt::Display for Wallet { #[derive(Debug, Deserialize, Clone)] pub struct ConsensusConfigData { - pub t0: UTime, + pub t0: MassaTime, pub thread_count: u8, - pub genesis_timestamp: UTime, + pub genesis_timestamp: MassaTime, pub delta_f0: u64, pub max_block_size: u32, pub operation_validity_periods: u64,