Skip to content

Commit

Permalink
fix: avoid implicit using of the time crate (#3562)
Browse files Browse the repository at this point in the history
Description
---
This PR removes implicit `time` crate dependency where possible.

Motivation and Context
---
`chrono` crate uses a deprecated version of the `time` crate that has security issues.
As a result of the investigation, it was found that `chrono` supports `time` for compatibility,
but it's not required for most features and could be easily deactivated (by deactivating
default features).
All `time` relations removed except `tari_app_grpc` that depends on `tari_utilities` that also
needed the similar fix.

How Has This Been Tested?
---
CI
  • Loading branch information
therustmonk committed Nov 12, 2021
1 parent ec67798 commit 23e8398
Show file tree
Hide file tree
Showing 31 changed files with 184 additions and 279 deletions.
203 changes: 62 additions & 141 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion applications/tari_app_grpc/Cargo.toml
Expand Up @@ -13,7 +13,7 @@ tari_core = { path = "../../base_layer/core"}
tari_crypto = { git = "https://github.com/tari-project/tari-crypto.git", branch = "main" }
tari_comms = { path = "../../comms"}

chrono = "0.4.6"
chrono = { version = "0.4.19", default-features = false }
prost = "0.8"
prost-types = "0.8"
tonic = "0.5.2"
Expand Down
2 changes: 1 addition & 1 deletion applications/tari_base_node/Cargo.toml
Expand Up @@ -23,7 +23,7 @@ tari_shutdown = { path = "../../infrastructure/shutdown" }

anyhow = "1.0.32"
bincode = "1.3.1"
chrono = "0.4"
chrono = { version = "0.4.19", default-features = false }
config = { version = "0.9.3" }
either = "1.6.1"
futures = { version = "^0.3.16", default-features = false, features = ["alloc"] }
Expand Down
4 changes: 1 addition & 3 deletions applications/tari_console_wallet/Cargo.toml
Expand Up @@ -17,7 +17,7 @@ tari_app_grpc = { path = "../tari_app_grpc" }
tari_shutdown = { path = "../../infrastructure/shutdown" }
tari_key_manager = { path = "../../base_layer/key_manager" }

anyhow = "1.0.44"
chrono = { version = "0.4.19", default-features = false }
bitflags = "1.2.1"
futures = { version = "^0.3.16", default-features = false, features = ["alloc"] }
crossterm = { version = "0.17" }
Expand All @@ -34,8 +34,6 @@ strum_macros = "^0.19"
tokio = { version = "1.11", features = ["signal"] }
thiserror = "1.0.26"
tonic = "0.5.2"
time = { version = "0.3.4", features = ["formatting", "local-offset", "macros", "parsing"] }

tracing = "0.1.26"
tracing-opentelemetry = "0.15.0"
tracing-subscriber = "0.2.20"
Expand Down
Expand Up @@ -22,6 +22,7 @@

use crate::automation::{commands::WalletCommand, error::ParseError};

use chrono::{DateTime, Utc};
use core::str::SplitWhitespace;
use std::{
fmt::{Display, Formatter},
Expand All @@ -32,7 +33,6 @@ use tari_comms::multiaddr::Multiaddr;

use tari_common_types::types::PublicKey;
use tari_core::transactions::tari_amount::MicroTari;
use time::{format_description::well_known::Rfc3339, OffsetDateTime};

#[derive(Debug)]
pub struct ParsedCommand {
Expand Down Expand Up @@ -77,7 +77,7 @@ pub enum ParsedArgument {
Text(String),
Float(f64),
Int(u64),
Date(OffsetDateTime),
Date(DateTime<Utc>),
OutputToCSVFile(String),
CSVFileName(String),
Address(Multiaddr),
Expand Down Expand Up @@ -216,9 +216,9 @@ fn parse_make_it_rain(mut args: SplitWhitespace) -> Result<Vec<ParsedArgument>,
// start time utc or 'now'
let start_time = args.next().ok_or_else(|| ParseError::Empty("start time".to_string()))?;
let start_time = if start_time != "now" {
OffsetDateTime::parse(start_time, &Rfc3339)?
DateTime::parse_from_rfc3339(start_time)?.with_timezone(&Utc)
} else {
OffsetDateTime::now_utc()
Utc::now()
};
parsed_args.push(ParsedArgument::Date(start_time));

Expand Down
12 changes: 6 additions & 6 deletions applications/tari_console_wallet/src/automation/commands.rs
Expand Up @@ -21,6 +21,7 @@
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use super::error::CommandError;
use chrono::Utc;
use log::*;
use std::{
convert::TryFrom,
Expand Down Expand Up @@ -58,7 +59,6 @@ use tari_wallet::{
transaction_service::handle::{TransactionEvent, TransactionServiceHandle},
WalletSqlite,
};
use time::OffsetDateTime;
use tokio::{
sync::{broadcast, mpsc},
time::{sleep, timeout},
Expand Down Expand Up @@ -296,13 +296,13 @@ pub async fn make_it_rain(
// We are spawning this command in parallel, thus not collecting transaction IDs
tokio::task::spawn(async move {
// Wait until specified test start time
let now = OffsetDateTime::now_utc();
let now = Utc::now();
let delay_ms = if start_time > now {
println!(
"`make-it-rain` scheduled to start at {}: msg \"{}\"",
start_time, message
);
(start_time - now).whole_milliseconds() as u64
(start_time - now).num_milliseconds() as u64
} else {
0
};
Expand All @@ -314,7 +314,7 @@ pub async fn make_it_rain(
sleep(Duration::from_millis(delay_ms)).await;

let num_txs = (txps * duration as f64) as usize;
let started_at = OffsetDateTime::now_utc();
let started_at = Utc::now();

struct TransactionSendStats {
i: usize,
Expand Down Expand Up @@ -348,7 +348,7 @@ pub async fn make_it_rain(
ParsedArgument::Text(message.clone()),
];
// Manage transaction submission rate
let actual_ms = (OffsetDateTime::now_utc() - started_at).whole_milliseconds() as i64;
let actual_ms = (Utc::now() - started_at).num_milliseconds();
let target_ms = (i as f64 / (txps / 1000.0)) as i64;
if target_ms - actual_ms > 0 {
// Maximum delay between Txs set to 120 s
Expand Down Expand Up @@ -420,7 +420,7 @@ pub async fn make_it_rain(
num_txs,
transaction_type,
message,
OffsetDateTime::now_utc(),
Utc::now(),
);
});

Expand Down
5 changes: 1 addition & 4 deletions applications/tari_console_wallet/src/automation/error.rs
Expand Up @@ -34,7 +34,6 @@ use tari_wallet::{
transaction_service::error::TransactionServiceError,
};
use thiserror::Error;
use time::error::ComponentRange;
use tokio::task::JoinError;

pub const LOG_TARGET: &str = "wallet::automation::error";
Expand Down Expand Up @@ -88,9 +87,7 @@ pub enum ParseError {
#[error("Failed to parse int.")]
Int(#[from] ParseIntError),
#[error("Failed to parse date. {0}")]
Date(#[from] time::error::Parse),
#[error("Failed to convert time. {0}")]
TimeRange(#[from] ComponentRange),
Date(#[from] chrono::ParseError),
#[error("Failed to parse a net address.")]
Address,
#[error("Invalid combination of arguments ({0}).")]
Expand Down
6 changes: 3 additions & 3 deletions applications/tari_console_wallet/src/recovery.rs
Expand Up @@ -20,6 +20,7 @@
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use chrono::offset::Local;
use futures::FutureExt;
use log::*;
use rustyline::Editor;
Expand All @@ -35,7 +36,6 @@ use tari_wallet::{

use crate::wallet_modes::PeerConfig;
use tari_key_manager::cipher_seed::CipherSeed;
use time::OffsetDateTime;
use tokio::sync::broadcast;

pub const LOG_TARGET: &str = "wallet::recovery";
Expand Down Expand Up @@ -126,14 +126,14 @@ pub async fn wallet_recovery(wallet: &WalletSqlite, base_node_config: &PeerConfi
debug!(
target: LOG_TARGET,
"{}: Recovery process {}% complete ({} of {} utxos).",
OffsetDateTime::now_local().unwrap(),
Local::now(),
percentage_progress,
current,
total
);
println!(
"{}: Recovery process {}% complete ({} of {} utxos).",
OffsetDateTime::now_local().unwrap(),
Local::now(),
percentage_progress,
current,
total
Expand Down
Expand Up @@ -9,9 +9,7 @@
// notification, the UI should go there if I click on it.

use crate::ui::{components::Component, state::AppState};
use anyhow::Error;
use tari_comms::runtime::Handle;
use time::{error::Format, format_description::FormatItem, macros::format_description};
use tui::{
backend::Backend,
layout::{Constraint, Layout, Rect},
Expand All @@ -21,16 +19,14 @@ use tui::{
Frame,
};

const DT_FORMAT: &[FormatItem<'static>] = format_description!("[year]-[month]-[day] [hour]-[minute]-[second] ");

pub struct NotificationTab {}

impl NotificationTab {
pub fn new() -> Self {
Self {}
}

fn draw_notifications<B>(&mut self, f: &mut Frame<B>, area: Rect, app_state: &AppState) -> Result<(), Error>
fn draw_notifications<B>(&mut self, f: &mut Frame<B>, area: Rect, app_state: &AppState)
where B: Backend {
let block = Block::default().borders(Borders::ALL).title(Span::styled(
"Notifications",
Expand All @@ -46,16 +42,17 @@ impl NotificationTab {
.iter()
.rev()
.map(|(time, line)| {
Ok(Spans::from(vec![
Span::styled(time.format(&DT_FORMAT)?, Style::default().fg(Color::LightGreen)),
Spans::from(vec![
Span::styled(
time.format("%Y-%m-%d %H:%M:%S ").to_string(),
Style::default().fg(Color::LightGreen),
),
Span::raw(line),
]))
])
})
.collect::<Result<Vec<Spans>, Format>>()
.unwrap();
.collect::<Vec<_>>();
let paragraph = Paragraph::new(text).wrap(Wrap { trim: true });
f.render_widget(paragraph, notifications_area[0]);
Ok(())
}
}

Expand All @@ -64,9 +61,7 @@ impl<B: Backend> Component<B> for NotificationTab {
let areas = Layout::default()
.constraints([Constraint::Min(42)].as_ref())
.split(area);
if let Err(err) = self.draw_notifications(f, areas[0], app_state) {
log::error!("Notification tab rendering failed: {}", err);
}
self.draw_notifications(f, areas[0], app_state);
}

fn on_tick(&mut self, app_state: &mut AppState) {
Expand Down
Expand Up @@ -6,9 +6,8 @@ use crate::ui::{
widgets::{draw_dialog, MultiColumnList, WindowedListState},
MAX_WIDTH,
};
use anyhow::Error;
use chrono::{DateTime, Local};
use tari_common_types::transaction::{TransactionDirection, TransactionStatus};
use time::{format_description::FormatItem, macros::format_description, UtcOffset};
use tokio::runtime::Handle;
use tui::{
backend::Backend,
Expand All @@ -19,8 +18,6 @@ use tui::{
Frame,
};

const DT_FORMAT: &[FormatItem<'static>] = format_description!("[year]-[month]-[day] [hour]:[minute]:[second]");

pub struct TransactionsTab {
balance: Balance,
selected_tx_list: SelectedTransactionList,
Expand All @@ -44,7 +41,7 @@ impl TransactionsTab {
}
}

fn draw_transaction_lists<B>(&mut self, f: &mut Frame<B>, area: Rect, app_state: &AppState) -> Result<(), Error>
fn draw_transaction_lists<B>(&mut self, f: &mut Frame<B>, area: Rect, app_state: &AppState)
where B: Backend {
let (pending_constraint, completed_constraint) = if app_state.get_pending_txs().is_empty() {
self.selected_tx_list = SelectedTransactionList::CompletedTxs;
Expand All @@ -69,20 +66,12 @@ impl TransactionsTab {
.title(Span::styled("(P)ending Transactions", style));
f.render_widget(block, list_areas[0]);

self.draw_pending_transactions(f, list_areas[0], app_state)?;
self.draw_completed_transactions(f, list_areas[1], app_state)?;
Ok(())
self.draw_pending_transactions(f, list_areas[0], app_state);
self.draw_completed_transactions(f, list_areas[1], app_state);
}

fn draw_pending_transactions<B>(
&mut self,
f: &mut Frame<B>,
area: Rect,
app_state: &AppState,
) -> Result<(), Error>
where
B: Backend,
{
fn draw_pending_transactions<B>(&mut self, f: &mut Frame<B>, area: Rect, app_state: &AppState)
where B: Backend {
// Pending Transactions
self.pending_list_state.set_num_items(app_state.get_pending_txs().len());
let mut pending_list_state = self
Expand Down Expand Up @@ -125,10 +114,9 @@ impl TransactionsTab {
};
column1_items.push(ListItem::new(Span::styled(format!("{}", t.amount), amount_style)));
}
let offset = UtcOffset::current_local_offset()?;
let local_time = t.timestamp.replace_offset(offset);
let local_time = DateTime::<Local>::from_utc(t.timestamp, Local::now().offset().to_owned());
column2_items.push(ListItem::new(Span::styled(
local_time.format(&DT_FORMAT)?,
format!("{}", local_time.format("%Y-%m-%d %H:%M:%S")),
Style::default().fg(text_color),
)));
column3_items.push(ListItem::new(Span::styled(
Expand All @@ -146,18 +134,10 @@ impl TransactionsTab {
.add_column(Some("Local Date/Time"), Some(20), column2_items)
.add_column(Some("Message"), None, column3_items);
column_list.render(f, area, &mut pending_list_state);
Ok(())
}

fn draw_completed_transactions<B>(
&mut self,
f: &mut Frame<B>,
area: Rect,
app_state: &AppState,
) -> Result<(), Error>
where
B: Backend,
{
fn draw_completed_transactions<B>(&mut self, f: &mut Frame<B>, area: Rect, app_state: &AppState)
where B: Backend {
// Completed Transactions
let style = if self.selected_tx_list == SelectedTransactionList::CompletedTxs {
Style::default().fg(Color::Magenta).add_modifier(Modifier::BOLD)
Expand Down Expand Up @@ -223,10 +203,9 @@ impl TransactionsTab {
let amount_style = Style::default().fg(color);
column1_items.push(ListItem::new(Span::styled(format!("{}", t.amount), amount_style)));
}
let offset = UtcOffset::current_local_offset()?;
let local_time = t.timestamp.replace_offset(offset);
let local_time = DateTime::<Local>::from_utc(t.timestamp, Local::now().offset().to_owned());
column2_items.push(ListItem::new(Span::styled(
local_time.format(&DT_FORMAT)?,
format!("{}", local_time.format("%Y-%m-%d %H:%M:%S")),
Style::default().fg(text_color),
)));
let status = if (t.cancelled || !t.valid) && t.status == TransactionStatus::Coinbase {
Expand All @@ -253,7 +232,6 @@ impl TransactionsTab {
.add_column(Some("Status"), None, column3_items);

column_list.render(f, area, &mut completed_list_state);
Ok(())
}

fn draw_detailed_transaction<B>(&self, f: &mut Frame<B>, area: Rect, app_state: &AppState)
Expand Down Expand Up @@ -366,10 +344,9 @@ impl TransactionsTab {
};
let status = Span::styled(status_msg, Style::default().fg(Color::White));
let message = Span::styled(tx.message.as_str(), Style::default().fg(Color::White));
// TODO: Get Local from UTC
let local_time = tx.timestamp;
let local_time = DateTime::<Local>::from_utc(tx.timestamp, Local::now().offset().to_owned());
let timestamp = Span::styled(
format!("{}", local_time.format(&DT_FORMAT).unwrap()),
format!("{}", local_time.format("%Y-%m-%d %H:%M:%S")),
Style::default().fg(Color::White),
);
let excess = Span::styled(tx.excess_signature.as_str(), Style::default().fg(Color::White));
Expand Down Expand Up @@ -469,9 +446,7 @@ impl<B: Backend> Component<B> for TransactionsTab {
let instructions = Paragraph::new(Spans::from(span_vec)).wrap(Wrap { trim: true });
f.render_widget(instructions, areas[1]);

if let Err(err) = self.draw_transaction_lists(f, areas[2], app_state) {
log::error!("Can't draw transactions list: {}", err);
}
self.draw_transaction_lists(f, areas[2], app_state);
self.draw_detailed_transaction(f, areas[3], app_state);

if let Some(msg) = self.error_message.clone() {
Expand Down

0 comments on commit 23e8398

Please sign in to comment.