Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft sp-time #3298

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
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
27 changes: 27 additions & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,7 @@ members = [
"substrate/primitives/std",
"substrate/primitives/storage",
"substrate/primitives/test-primitives",
"substrate/primitives/time",
"substrate/primitives/timestamp",
"substrate/primitives/tracing",
"substrate/primitives/transaction-pool",
Expand Down
2 changes: 2 additions & 0 deletions substrate/frame/timestamp/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ frame-support = { path = "../support", default-features = false }
frame-system = { path = "../system", default-features = false }
sp-inherents = { path = "../../primitives/inherents", default-features = false }
sp-io = { path = "../../primitives/io", default-features = false, optional = true }
sp-time = { path = "../../primitives/time", default-features = false }
sp-runtime = { path = "../../primitives/runtime", default-features = false }
sp-std = { path = "../../primitives/std", default-features = false }
sp-storage = { path = "../../primitives/storage", default-features = false }
Expand All @@ -47,6 +48,7 @@ std = [
"scale-info/std",
"sp-core/std",
"sp-inherents/std",
"sp-time/std",
"sp-io?/std",
"sp-runtime/std",
"sp-std/std",
Expand Down
9 changes: 9 additions & 0 deletions substrate/frame/timestamp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ pub mod weights;
use frame_support::traits::{OnTimestampSet, Time, UnixTime};
use sp_runtime::traits::{AtLeast32Bit, SaturatedConversion, Scale, Zero};
use sp_std::{cmp, result};
use sp_time::{InstantProvider, UnixDuration, UnixInstant};
use sp_timestamp::{InherentError, InherentType, INHERENT_IDENTIFIER};
pub use weights::WeightInfo;

Expand Down Expand Up @@ -379,3 +380,11 @@ impl<T: Config> UnixTime for Pallet<T> {
core::time::Duration::from_millis(now.saturated_into::<u64>())
}
}

impl<T: Config> InstantProvider<UnixInstant> for Pallet<T> {
fn now() -> UnixInstant {
let ms_since_epoch: u128 = Now::<T>::get().saturated_into();

UnixInstant::from_epoch_start(UnixDuration::from_millis(ms_since_epoch))
}
}
21 changes: 18 additions & 3 deletions substrate/frame/timestamp/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,14 @@

//! Tests for the Timestamp module.

use crate::mock::*;
use crate::{mock::*, Now};
use frame_support::assert_ok;
use sp_time::InstantProvider;

#[test]
fn timestamp_works() {
new_test_ext().execute_with(|| {
crate::Now::<Test>::put(46);
Now::<Test>::put(46);
assert_ok!(Timestamp::set(RuntimeOrigin::none(), 69));
assert_eq!(Timestamp::now(), 69);
assert_eq!(Some(69), get_captured_moment());
Expand All @@ -47,7 +48,21 @@ fn double_timestamp_should_fail() {
)]
fn block_period_minimum_enforced() {
new_test_ext().execute_with(|| {
crate::Now::<Test>::put(44);
Now::<Test>::put(44);
let _ = Timestamp::set(RuntimeOrigin::none(), 46);
});
}

#[test]
fn instant_provider_works() {
new_test_ext().execute_with(|| {
for i in 0..10 {
Now::<Test>::put(i * 1_000);

let instant = <Timestamp as InstantProvider<_>>::now();
let ms = Now::<Test>::get();

assert_eq!(ms as u128, instant.since_epoch.ns / 1_000_000);
}
});
}
34 changes: 34 additions & 0 deletions substrate/primitives/time/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
[package]
name = "sp-time"
version = "0.1.0"
authors.workspace = true
edition.workspace = true
repository.workspace = true
license.workspace = true

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] }
scale-info = { version = "2.10.0", default-features = false, features = ["derive"] }
sp-arithmetic = { path = "../arithmetic", default-features = false }
sp-runtime = { path = "../runtime", default-features = false }
sp-core = { path = "../core", optional = true }
arbitrary = { version = "1.3.2", features = ["derive"], optional = true }

[lints]
workspace = true

[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]

[features]
default = ["std"]
std = [
"dep:arbitrary",
"sp-core/std",
"sp-runtime/std",
"codec/std",
"scale-info/std",
"sp-arithmetic/std"
]
144 changes: 144 additions & 0 deletions substrate/primitives/time/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Substrate time and duration types.
//!
//! Main design goal of this API is to KISS (Keep It Simple and Stupid) and to still fulfill our
//! needs. This means to rely on already existing conventions as much as possible.

#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(feature = "std")]
pub mod mock;
pub mod provider;
pub mod unix;

pub use unix::{UnixDuration, UnixInstant};

use codec::FullCodec;
use core::{
cmp::{Eq, PartialOrd},
fmt::Debug,
};
use scale_info::TypeInfo;
use sp_arithmetic::traits::{Bounded, CheckedAdd, CheckedSub, Zero};
use sp_runtime::traits::Member;

/// Provides the current time.
// NOTE: we cannot use an associated tye here because it would result in the `Instant cannot be made
// into an object` error.
pub trait InstantProvider<I: Instant> {
/// Returns the current time.
fn now() -> I;
}

/// Provide the time at genesis of this chain.
///
/// Can be used to calculate relative times since the inception of the chain. This can be useful for
/// things like vesting or other timed locks.
///
/// It is decoupled from the the normal `InstantProvider` because there can be pallets that only
/// need to know the absolute time.
pub trait GenesisInstantProvider<I: Instant>: InstantProvider<I> {
/// Returns the time at genesis.
///
/// The exact value of this is defined by the runtime.
fn genesis() -> I;
}

/// Marker trait for `InstantProvider`s where `now() <= now()` always holds.
///
/// `InstantProvider`s must saturate in the overflow case.
pub trait MonotonicIncrease {}

/// Marker trait for `InstantProvider`s where `now() < now()` always holds.
///
/// Note this may not hold in the saturating case.
pub trait StrictMonotonicIncrease: MonotonicIncrease {}

/// An instant or "time point".
pub trait Instant:
Member
+ FullCodec
+ TypeInfo
+ PartialOrd
+ Eq
+ Bounded
+ Debug
// If it turns out that our API is bad, then devs can still use UNIX formats:
+ TryFrom<UnixInstant>
+ TryInto<UnixInstant>
{
/// A difference (aka. Delta) between two `Instant`s.
type Duration: Duration;

/// Try to increase `self` by `delta`.
///
/// This does not use the standard `CheckedAdd` trait since that would require the argument to
/// be of type `Self`.
fn checked_add(&self, delta: &Self::Duration) -> Option<Self>;

fn saturating_add(&self, delta: &Self::Duration) -> Self {
self.checked_add(delta).unwrap_or_else(|| Self::max_value())
}

/// Try to decrease `self` by `delta`.
fn checked_sub(&self, delta: &Self::Duration) -> Option<Self>;

fn saturating_sub(&self, delta: &Self::Duration) -> Self {
self.checked_sub(delta).unwrap_or_else(|| Self::min_value())
}

/// How long it has been since `past`.
///
/// `None` is returned if the time is in the future. Note that this function glues together the `Self::Duration` and `Self` types.
fn since(&self, past: &Self) -> Option<Self::Duration>;

/// How long it is until `future`.
///
/// `None` is returned if the time is in the past. Note that this function glues together the `Self::Duration` and `Self` types.
fn until(&self, future: &Self) -> Option<Self::Duration>;
}

/// A duration or "time interval".
///
/// Durations MUST always be positive.
pub trait Duration:
Member
+ FullCodec
+ TypeInfo
+ PartialOrd
+ Eq
+ Debug
+ Bounded
+ CheckedAdd
+ CheckedSub
+ Zero
// If it turns out that our API is bad, then devs can still use UNIX formats:
+ TryFrom<UnixDuration>
+ TryInto<UnixDuration>
{
/// Scale the duration by a factor.
fn checked_mul_int(&self, other: u128) -> Option<Self>;

fn saturating_mul_int(&self, other: u128) -> Self {
self.checked_mul_int(other).unwrap_or_else(|| Self::max_value())
}

/// Divide the duration by a factor.
fn checked_div_int(&self, other: u128) -> Option<Self>;
}
52 changes: 52 additions & 0 deletions substrate/primitives/time/src/mock.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Testing helpers that can be re-used by external crates.

use crate::Instant;
use arbitrary::{Arbitrary, Unstructured};
use sp_runtime::traits::Zero;

pub struct InstantFuzzer<I>(core::marker::PhantomData<I>);

impl<I> InstantFuzzer<I>
where
for<'a> I: Instant + Arbitrary<'a>,
for<'a> I::Duration: Arbitrary<'a>,
{
pub fn fuzz() {
Self::prop_duration_is_not_negative();
}

/// Ensure that a `Duration` is never negative.
fn prop_duration_is_not_negative() {
Self::with_durations(1_000_000, |d| assert!(d >= I::Duration::zero()));
}

fn with_durations(reps: u32, f: impl Fn(I::Duration)) {
for _ in 0..reps {
let seed = u32::arbitrary(&mut Unstructured::new(&[0; 4])).unwrap();
f(Self::duration(seed));
}
}

fn duration(seed: u32) -> I::Duration {
let seed = sp_core::blake2_256(&seed.to_le_bytes());
let mut unstructured = Unstructured::new(&seed);
I::Duration::arbitrary(&mut unstructured).unwrap()
}
}
Loading
Loading