Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 58 additions & 7 deletions src/utils/rpc/primitive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,13 +95,21 @@ fn epoch_to_string(value: u64) -> String {
epoch.length(),
)
}
// The value comes from the RPC server, so it may be out of the range chrono can represent
fn timestamp_to_string(value: u64) -> String {
let dt = Local.timestamp_millis_opt(value as i64).unwrap();
format!("{} ({})", value, dt)
match i64::try_from(value)
.ok()
.and_then(|millis| Local.timestamp_millis_opt(millis).single())
{
Some(dt) => format!("{} ({})", value, dt),
None => format!("{} (invalid timestamp)", value),
}
}
fn since_to_string(value: u64) -> String {
let since = ckb_sdk::Since::from_raw_value(value);
let (ty, inner_value) = since.extract_metric().unwrap();
let Some((ty, inner_value)) = since.extract_metric() else {
return format!("0x{:x} (invalid since)", value);
};
let prefix = if since.is_absolute() {
"absolute"
} else {
Expand All @@ -118,10 +126,13 @@ fn since_to_string(value: u64) -> String {
epoch.length()
)
}
SinceType::Timestamp => format!(
"timestamp({})",
Local.timestamp_opt(inner_value as i64, 0).unwrap()
),
SinceType::Timestamp => match i64::try_from(inner_value)
.ok()
.and_then(|secs| Local.timestamp_opt(secs, 0).single())
{
Some(dt) => format!("timestamp({})", dt),
None => format!("timestamp({}, invalid)", inner_value),
},
};
format!("0x{:x} ({} {})", value, prefix, value_string)
}
Expand All @@ -145,3 +156,43 @@ impl_u64_serde!(
epoch_to_string
);
impl_u64_serde!(Since, SinceVisitor, rpc_types::Uint64, since_to_string);

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_out_of_range_timestamp_does_not_panic() {
// 2025-06-15 15:06:40 UTC, still June 2025 in any time zone
assert!(timestamp_to_string(1_750_000_000_000).starts_with("1750000000000 (2025-06-"));
assert_eq!(
timestamp_to_string(9_000_000_000_000_000),
"9000000000000000 (invalid timestamp)"
);
assert_eq!(
timestamp_to_string(u64::MAX),
format!("{} (invalid timestamp)", u64::MAX)
);
}

#[test]
fn test_invalid_since_does_not_panic() {
// absolute timestamp since with the largest value
let since = 0x40ff_ffff_ffff_ffffu64;
assert_eq!(
since_to_string(since),
format!(
"0x{:x} (absolute timestamp({}, invalid))",
since, 0x00ff_ffff_ffff_ffffu64
)
);
// metric flag 0b11 is not a valid since type
let since = 0x6000_0000_0000_0000u64;
assert_eq!(
since_to_string(since),
format!("0x{:x} (invalid since)", since)
);
// a valid block number since is still rendered
assert_eq!(since_to_string(100), "0x64 (absolute block(100))");
}
}
Loading