1
// Copyright (C) Moondance Labs Ltd.
2
// This file is part of Tanssi.
3

            
4
// Tanssi is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8

            
9
// Tanssi is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13

            
14
// You should have received a copy of the GNU General Public License
15
// along with Tanssi.  If not, see <http://www.gnu.org/licenses/>.
16

            
17
use std::sync::atomic::{AtomicU64, Ordering};
18

            
19
static TIMESTAMP: AtomicU64 = AtomicU64::new(0);
20

            
21
/// Provide a mock duration starting at 0 in millisecond for timestamp inherent.
22
/// Each call will increment timestamp by slot_duration making Aura think time has passed.
23
pub struct MockTimestampInherentDataProvider;
24

            
25
impl MockTimestampInherentDataProvider {
26
35136
    pub fn advance_timestamp(slot_duration: u64) {
27
35136
        if TIMESTAMP.load(Ordering::SeqCst) == 0 {
28
1206
            // Initialize timestamp inherent provider
29
1206
            TIMESTAMP.store(
30
1206
                sp_timestamp::Timestamp::current().as_millis(),
31
1206
                Ordering::SeqCst,
32
1206
            );
33
33930
        } else {
34
33930
            TIMESTAMP.fetch_add(slot_duration, Ordering::SeqCst);
35
33930
        }
36
35136
    }
37

            
38
35136
    pub fn load() -> u64 {
39
35136
        TIMESTAMP.load(Ordering::SeqCst)
40
35136
    }
41
}
42

            
43
#[async_trait::async_trait]
44
impl sp_inherents::InherentDataProvider for MockTimestampInherentDataProvider {
45
    async fn provide_inherent_data(
46
        &self,
47
        inherent_data: &mut sp_inherents::InherentData,
48
70272
    ) -> Result<(), sp_inherents::Error> {
49
35136
        inherent_data.put_data(
50
            sp_timestamp::INHERENT_IDENTIFIER,
51
35136
            &TIMESTAMP.load(Ordering::SeqCst),
52
        )
53
70272
    }
54

            
55
    async fn try_handle_error(
56
        &self,
57
        _identifier: &sp_inherents::InherentIdentifier,
58
        _error: &[u8],
59
    ) -> Option<Result<(), sp_inherents::Error>> {
60
        // The pallet never reports error.
61
        None
62
    }
63
}