Add getBlockTime rpc api (#7130)

* Add getBlockTime rpc api

* Add getBlockTime to docs

* Fix duration rounding for common tick/slot durations; add slot duration calculation

* Expose slots_per_year

* Use genesis values instead of clock defaults to calculate block offset

* Add get-block-time cli subcommand

* Fix test_rent: decrease magic number usage
This commit is contained in:
Tyera Eulberg
2019-11-26 00:40:36 -07:00
committed by GitHub
parent 280315a314
commit 58c144ee55
12 changed files with 336 additions and 47 deletions

View File

@@ -38,27 +38,58 @@ pub fn years_as_slots(years: f64, tick_duration: &Duration, ticks_per_slot: u64)
/ ticks_per_slot as f64
}
/// From slots per year to tick_duration
pub fn slot_duration_from_slots_per_year(slots_per_year: f64) -> Duration {
// Regarding division by zero potential below: for some reason, if Rust stores an `inf` f64 and
// then converts it to a u64 on use, it always returns 0, as opposed to std::u64::MAX or any
// other huge value
let slot_in_ns = (SECONDS_PER_YEAR * 1_000_000_000.0) / slots_per_year;
Duration::from_nanos(slot_in_ns as u64)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_years_as_slots() {
let tick_duration = Duration::from_millis(1000 / 160);
let tick_duration = Duration::from_micros(1000 * 1000 / 160);
// interestingly large numbers with 160 ticks/second
assert_eq!(years_as_slots(0.0, &tick_duration, 4) as u64, 0);
assert_eq!(
years_as_slots(1.0 / 12f64, &tick_duration, 4) as u64,
109_572_659
105_189_753
);
assert_eq!(years_as_slots(1.0, &tick_duration, 4) as u64, 1_314_871_916);
assert_eq!(years_as_slots(1.0, &tick_duration, 4) as u64, 1_262_277_039);
let tick_duration = Duration::from_millis(1000);
let tick_duration = Duration::from_micros(1000 * 1000);
// one second in years with one tick per second + one tick per slot
assert_eq!(
years_as_slots(1.0 / SECONDS_PER_YEAR, &tick_duration, 1),
1.0
);
}
#[test]
fn test_slot_duration_from_slots_per_year() {
let slots_per_year = 1_262_277_039.0;
let ticks_per_slot = 4;
assert_eq!(
slot_duration_from_slots_per_year(slots_per_year),
Duration::from_micros(1000 * 1000 / 160) * ticks_per_slot
);
assert_eq!(
slot_duration_from_slots_per_year(0.0),
Duration::from_micros(0) * ticks_per_slot
);
let slots_per_year = SECONDS_PER_YEAR;
let ticks_per_slot = 1;
assert_eq!(
slot_duration_from_slots_per_year(slots_per_year),
Duration::from_millis(1000) * ticks_per_slot
);
}
}