Skip to content

Commit

Permalink
fix: use time crate instead of chrono (#3527)
Browse files Browse the repository at this point in the history
Description
---
Replaces `chrono` crate to `time` where possible.

Motivation and Context
---
`chrono` crate depends on `time`, but is not actively maintained.
There is a known security issue:
chronotope/chrono#578

How Has This Been Tested?
---
In progress...
  • Loading branch information
therustmonk authored Nov 9, 2021
1 parent 0ae5fbd commit d211031
Show file tree
Hide file tree
Showing 10 changed files with 111 additions and 77 deletions.
46 changes: 23 additions & 23 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions applications/tari_console_wallet/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,8 @@ tari_app_grpc = { path = "../tari_app_grpc" }
tari_shutdown = { path = "../../infrastructure/shutdown" }
tari_key_manager = { path = "../../base_layer/key_manager" }

anyhow = "1.0.44"
bitflags = "1.2.1"
chrono = { version = "0.4.6", features = ["serde"] }
chrono-english = "0.1"
futures = { version = "^0.3.16", default-features = false, features = ["alloc"] }
crossterm = { version = "0.17" }
rand = "0.8"
Expand All @@ -35,6 +34,7 @@ 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"
Expand Down
4 changes: 3 additions & 1 deletion applications/tari_console_wallet/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,12 +72,14 @@ Make it rain! Send many transactions to a public key or emoji id.

`<type>` can be `negotiated` or `one_sided`

`<start time>` is a string in RFC3339 format or `now`

example:

```
$ tari_console_wallet --command "make-it-rain 1 10 8000 100 now c69fbe5f05a304eaec65d5f234a6aa258a90b8bb5b9ceffea779653667ef2108 negotiated makin it rain yo"
1. make-it-rain 1 10 8000 µT 100 µT 2021-03-26 10:03:30.459157 UTC c69fbe5f05a304eaec65d5f234a6aa258a90b8bb5b9ceffea779653667ef2108 negotiated makin it rain yo
1. make-it-rain 1 10 8000 µT 100 µT 2021-03-26T10:03:30Z c69fbe5f05a304eaec65d5f234a6aa258a90b8bb5b9ceffea779653667ef2108 negotiated makin it rain yo
Monitoring 10 sent transactions to Broadcast stage...
Done! All transactions monitored to Broadcast stage.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@

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

use chrono::{DateTime, Utc};
use chrono_english::{parse_date_string, Dialect};
use core::str::SplitWhitespace;
use std::{
fmt::{Display, Formatter},
Expand All @@ -34,6 +32,7 @@ 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 @@ -78,7 +77,7 @@ pub enum ParsedArgument {
Text(String),
Float(f64),
Int(u64),
Date(DateTime<Utc>),
Date(OffsetDateTime),
OutputToCSVFile(String),
CSVFileName(String),
Address(Multiaddr),
Expand Down Expand Up @@ -216,11 +215,10 @@ 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 now = Utc::now();
let start_time = if start_time != "now" {
parse_date_string(start_time, now, Dialect::Uk).map_err(ParseError::Date)?
OffsetDateTime::parse(start_time, &Rfc3339)?
} else {
now
OffsetDateTime::now_utc()
};
parsed_args.push(ParsedArgument::Date(start_time));

Expand Down
14 changes: 7 additions & 7 deletions applications/tari_console_wallet/src/automation/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ use std::{
time::{Duration, Instant},
};

use chrono::{DateTime, Utc};
use futures::FutureExt;
use strum_macros::{Display, EnumIter, EnumString};
use tari_crypto::ristretto::pedersen::PedersenCommitmentFactory;
Expand Down Expand Up @@ -59,6 +58,7 @@ use tari_wallet::{
transaction_service::handle::{TransactionEvent, TransactionServiceHandle},
WalletSqlite,
};
use time::OffsetDateTime;
use tokio::{
sync::{broadcast, mpsc},
time::{sleep, timeout},
Expand Down Expand Up @@ -274,7 +274,7 @@ pub async fn make_it_rain(
}?;

let start_time = match args[4].clone() {
Date(dt) => Ok(dt as DateTime<Utc>),
Date(dt) => Ok(dt),
_ => Err(CommandError::Argument),
}?;

Expand All @@ -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 = Utc::now();
let now = OffsetDateTime::now_utc();
let delay_ms = if start_time > now {
println!(
"`make-it-rain` scheduled to start at {}: msg \"{}\"",
start_time, message
);
(start_time - now).num_milliseconds() as u64
(start_time - now).whole_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 = Utc::now();
let started_at = OffsetDateTime::now_utc();

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 = (Utc::now() - started_at).num_milliseconds();
let actual_ms = (OffsetDateTime::now_utc() - started_at).whole_milliseconds() as i64;
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,
Utc::now()
OffsetDateTime::now_utc(),
);
});

Expand Down
6 changes: 4 additions & 2 deletions applications/tari_console_wallet/src/automation/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@

use std::num::{ParseFloatError, ParseIntError};

use chrono_english::DateError;
use log::*;
use tari_common::exit_codes::ExitCodes;
use tari_core::transactions::{
Expand All @@ -35,6 +34,7 @@ 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,7 +88,9 @@ pub enum ParseError {
#[error("Failed to parse int.")]
Int(#[from] ParseIntError),
#[error("Failed to parse date. {0}")]
Date(#[from] DateError),
Date(#[from] time::error::Parse),
#[error("Failed to convert time. {0}")]
TimeRange(#[from] ComponentRange),
#[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
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
// 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 @@ -36,6 +35,7 @@ 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).",
Local::now(),
OffsetDateTime::now_local().unwrap(),
percentage_progress,
current,
total
);
println!(
"{}: Recovery process {}% complete ({} of {} utxos).",
Local::now(),
OffsetDateTime::now_local().unwrap(),
percentage_progress,
current,
total
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@
// 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 @@ -19,14 +21,16 @@ 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)
fn draw_notifications<B>(&mut self, f: &mut Frame<B>, area: Rect, app_state: &AppState) -> Result<(), Error>
where B: Backend {
let block = Block::default().borders(Borders::ALL).title(Span::styled(
"Notifications",
Expand All @@ -37,22 +41,21 @@ impl NotificationTab {
.constraints([Constraint::Min(42)].as_ref())
.margin(1)
.split(area);
let mut text: Vec<Spans> = app_state
let text = app_state
.get_notifications()
.iter()
.rev()
.map(|(time, line)| {
Spans::from(vec![
Span::styled(
time.format("%Y-%m-%d %H:%M:%S ").to_string(),
Style::default().fg(Color::LightGreen),
),
Ok(Spans::from(vec![
Span::styled(time.format(&DT_FORMAT)?, Style::default().fg(Color::LightGreen)),
Span::raw(line),
])
]))
})
.collect();
text.reverse();
let paragraph = Paragraph::new(text.clone()).wrap(Wrap { trim: true });
.collect::<Result<Vec<Spans>, Format>>()
.unwrap();
let paragraph = Paragraph::new(text).wrap(Wrap { trim: true });
f.render_widget(paragraph, notifications_area[0]);
Ok(())
}
}

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

fn on_tick(&mut self, app_state: &mut AppState) {
Expand Down
Loading

0 comments on commit d211031

Please sign in to comment.