Skip to content

Commit

Permalink
Merge branch 'main' into feature/execution/add_cautious_bassoon
Browse files Browse the repository at this point in the history
  • Loading branch information
yvan-sraka authored Dec 12, 2021
2 parents 9681461 + 46cdb7d commit 3276f1b
Show file tree
Hide file tree
Showing 52 changed files with 459 additions and 412 deletions.
18 changes: 7 additions & 11 deletions massa-api/src/public.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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<Public> {
Expand Down Expand Up @@ -100,7 +98,7 @@ impl Endpoints for API<Public> {
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,
Expand All @@ -122,8 +120,7 @@ impl Endpoints for API<Public> {
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
Expand Down Expand Up @@ -314,7 +311,7 @@ impl Endpoints for API<Public> {
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,
Expand Down Expand Up @@ -357,7 +354,7 @@ impl Endpoints for API<Public> {
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,
Expand Down Expand Up @@ -442,7 +439,7 @@ impl Endpoints for API<Public> {
.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 })
Expand All @@ -451,7 +448,6 @@ impl Endpoints for API<Public> {
}
})
})
.flatten()
.collect(),
blocks_created: blocks.remove(&address).ok_or(ApiError::NotFound)?,
involved_in_endorsements: endorsements
Expand Down
9 changes: 6 additions & 3 deletions massa-bootstrap/src/establisher.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) 2021 MASSA LABS <[email protected]>

#[cfg(not(test))]
use massa_time::UTime;
use massa_time::MassaTime;
#[cfg(not(test))]
use std::{io, net::SocketAddr};
#[cfg(not(test))]
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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<DefaultConnector> {
pub async fn get_connector(
&mut self,
timeout_duration: MassaTime,
) -> io::Result<DefaultConnector> {
Ok(DefaultConnector(timeout_duration))
}
}
Expand Down
16 changes: 8 additions & 8 deletions massa-bootstrap/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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(_) => {
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -158,8 +158,8 @@ pub async fn get_state(
bootstrap_settings: &'static BootstrapSettings,
mut establisher: Establisher,
version: Version,
genesis_timestamp: UTime,
end_timestamp: Option<UTime>,
genesis_timestamp: MassaTime,
end_timestamp: Option<MassaTime>,
) -> Result<
(
Option<ExportProofOfStake>,
Expand All @@ -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", {});
Expand All @@ -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");
}
}
Expand Down Expand Up @@ -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 {
Expand Down
6 changes: 3 additions & 3 deletions massa-bootstrap/src/messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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,
Expand Down Expand Up @@ -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..])?;
Expand Down
16 changes: 8 additions & 8 deletions massa-bootstrap/src/settings.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) 2021 MASSA LABS <[email protected]>

use massa_signature::PublicKey;
use massa_time::UTime;
use massa_time::MassaTime;
use serde::Deserialize;
use std::net::SocketAddr;

Expand Down Expand Up @@ -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<SocketAddr>,
/// 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,
}
6 changes: 3 additions & 3 deletions massa-bootstrap/src/tests/mock_establisher.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Copyright (c) 2021 MASSA LABS <[email protected]>

use massa_time::UTime;
use massa_time::MassaTime;
use std::io;
use std::net::SocketAddr;
use tokio::io::DuplexStream;
Expand Down Expand Up @@ -59,7 +59,7 @@ impl MockListener {
#[derive(Debug)]
pub struct MockConnector {
connection_connector_tx: mpsc::Sender<(Duplex, SocketAddr, oneshot::Sender<bool>)>,
timeout_duration: UTime,
timeout_duration: MassaTime,
}

impl MockConnector {
Expand Down Expand Up @@ -117,7 +117,7 @@ impl MockEstablisher {

pub async fn get_connector(
&mut self,
timeout_duration: UTime,
timeout_duration: MassaTime,
) -> std::io::Result<MockConnector> {
// create connector stream

Expand Down
4 changes: 2 additions & 2 deletions massa-bootstrap/src/tests/scenarios.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down
8 changes: 4 additions & 4 deletions massa-bootstrap/src/tests/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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)],
Expand All @@ -95,7 +95,7 @@ pub fn get_keys() -> (PrivateKey, PublicKey) {

pub async fn wait_consensus_command<F, T>(
consensus_command_receiver: &mut Receiver<ConsensusCommand>,
timeout: UTime,
timeout: MassaTime,
filter_map: F,
) -> Option<T>
where
Expand All @@ -116,7 +116,7 @@ where

pub async fn wait_network_command<F, T>(
network_command_receiver: &mut Receiver<NetworkCommand>,
timeout: UTime,
timeout: MassaTime,
filter_map: F,
) -> Option<T>
where
Expand Down
13 changes: 7 additions & 6 deletions massa-client/src/cmds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -190,7 +190,7 @@ impl Display for ExtendedWalletEntry {
pub struct ExtendedWallet(AddressHashMap<ExtendedWalletEntry>);

impl ExtendedWallet {
fn new(wallet: &Wallet, addresses_info: &Vec<AddressInfo>) -> Result<Self> {
fn new(wallet: &Wallet, addresses_info: &[AddressInfo]) -> Result<Self> {
Ok(ExtendedWallet(
addresses_info
.iter()
Expand Down Expand Up @@ -245,7 +245,7 @@ impl Command {
&self,
client: &Client,
wallet: &mut Wallet,
parameters: &Vec<String>,
parameters: &[String],
json: bool,
) -> Result<Box<dyn Output>> {
match self {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -663,6 +664,6 @@ async fn send_operation(
}

// TODO: ugly utilities functions
pub fn parse_vec<T: std::str::FromStr>(args: &Vec<String>) -> anyhow::Result<Vec<T>, T::Err> {
pub fn parse_vec<T: std::str::FromStr>(args: &[String]) -> anyhow::Result<Vec<T>, T::Err> {
args.iter().map(|x| x.parse::<T>()).collect()
}
4 changes: 2 additions & 2 deletions massa-client/src/tests/tools.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
extern crate toml_edit;

use massa_time::UTime;
use massa_time::MassaTime;
use std::fs;
use toml_edit::{value, Document};

Expand All @@ -9,7 +9,7 @@ pub fn _update_genesis_timestamp(config_path: &str) {
let mut doc = toml.parse::<Document>().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");
}
Loading

0 comments on commit 3276f1b

Please sign in to comment.