chore: Move time logic out of primitives (#173)

This commit is contained in:
Santiago Carmuega 2022-08-13 14:37:02 -03:00 committed by GitHub
parent d72f9e42de
commit aab58480a6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 16 additions and 21 deletions

View file

@ -2,6 +2,5 @@
mod fees;
mod model;
mod time;
pub use model::*;

View file

@ -6,6 +6,7 @@ use pallas_crypto::hash::{Hash, Hasher};
use pallas_primitives::{alonzo, babbage, byron};
use crate::hashes::ToHash;
use crate::time;
use crate::{Era, Error, MultiEraHeader};
impl<'b> MultiEraHeader<'b> {
@ -57,10 +58,15 @@ impl<'b> MultiEraHeader<'b> {
pub fn slot(&self) -> u64 {
match self {
MultiEraHeader::EpochBoundary(x) => x.to_abs_slot(),
MultiEraHeader::EpochBoundary(x) => {
time::byron_epoch_slot_to_absolute(x.consensus_data.epoch_id, 0)
}
MultiEraHeader::AlonzoCompatible(x) => x.header_body.slot,
MultiEraHeader::Babbage(x) => x.header_body.slot,
MultiEraHeader::Byron(x) => x.consensus_data.0.to_abs_slot(),
MultiEraHeader::Byron(x) => time::byron_epoch_slot_to_absolute(
x.consensus_data.0.epoch,
x.consensus_data.0.slot,
),
}
}

View file

@ -21,6 +21,7 @@ pub mod output;
pub mod probe;
pub mod signers;
mod support;
pub mod time;
pub mod tx;
pub mod withdrawals;
pub mod witnesses;

View file

@ -1,30 +1,16 @@
use super::{EbbHead, SlotId};
// TODO: is it safe to hardcode these values?
const WELLKNOWN_SLOT_LENGTH: u64 = 20; // 20 secs
const WELLKNOWN_EPOCH_LENGTH: u64 = 5 * 24 * 60 * 60; // 5 days
fn epoch_slot_to_absolute(epoch: u64, sub_epoch_slot: u64) -> u64 {
pub fn byron_epoch_slot_to_absolute(epoch: u64, sub_epoch_slot: u64) -> u64 {
((epoch * WELLKNOWN_EPOCH_LENGTH) / WELLKNOWN_SLOT_LENGTH) + sub_epoch_slot
}
impl SlotId {
pub fn to_abs_slot(&self) -> u64 {
epoch_slot_to_absolute(self.epoch, self.slot)
}
}
impl EbbHead {
pub fn to_abs_slot(&self) -> u64 {
epoch_slot_to_absolute(self.consensus_data.epoch_id, 0)
}
}
#[cfg(test)]
mod tests {
use pallas_codec::minicbor;
use crate::byron::Block;
use crate::{byron::Block, time::byron_epoch_slot_to_absolute};
type BlockWrapper = (u16, Block);
@ -32,13 +18,16 @@ mod tests {
fn knwon_slot_matches() {
// TODO: expand this test to include more test blocks
let block_idx = 1;
let block_str = include_str!("../../../test_data/byron1.block");
let block_str = include_str!("../../test_data/byron1.block");
let block_bytes = hex::decode(block_str).expect(&format!("bad block file {}", block_idx));
let (_, block): BlockWrapper = minicbor::decode(&block_bytes[..])
.expect(&format!("error decoding cbor for file {}", block_idx));
let computed_slot = block.header.consensus_data.0.to_abs_slot();
let computed_slot = byron_epoch_slot_to_absolute(
block.header.consensus_data.0.epoch,
block.header.consensus_data.0.slot,
);
assert_eq!(computed_slot, 4492794);
}