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
#![cfg_attr(not(feature = "std"), no_std)]
18
use frame_system::offchain::CreateInherent;
19
use frame_system::offchain::CreateSignedTransaction;
20
use {
21
    frame_system::{
22
        self as system, ensure_none, ensure_root, offchain::SubmitTransaction,
23
        pallet_prelude::BlockNumberFor,
24
    },
25
    sp_runtime::transaction_validity::{InvalidTransaction, TransactionValidity, ValidTransaction},
26
};
27

            
28
pub use pallet::*;
29
#[frame_support::pallet]
30
pub mod pallet {
31
    use {super::*, frame_support::pallet_prelude::*, frame_system::pallet_prelude::*};
32

            
33
    #[pallet::pallet]
34
    pub struct Pallet<T>(_);
35

            
36
    #[pallet::config]
37
    pub trait Config:
38
        CreateSignedTransaction<Call<Self>> + CreateInherent<Call<Self>> + frame_system::Config
39
    {
40
        /// Number of blocks of cooldown after unsigned transaction is included.
41
        ///
42
        /// This ensures that we only accept unsigned transactions once, every `UnsignedInterval`
43
        /// blocks.
44
        #[pallet::constant]
45
        type UnsignedInterval: Get<BlockNumberFor<Self>>;
46
    }
47

            
48
    #[pallet::storage]
49
    pub(super) type OffchainWorkerTestEnabled<T> = StorageValue<_, bool, ValueQuery>;
50

            
51
    /// Defines the block when next unsigned transaction will be accepted.
52
    ///
53
    /// To prevent spam of unsigned (and unpaid!) transactions on the network,
54
    /// we only allow one transaction every `T::UnsignedInterval` blocks.
55
    /// This storage entry defines when new transaction is going to be accepted.
56
    #[pallet::storage]
57
    pub(super) type NextUnsignedAt<T: Config> = StorageValue<_, BlockNumberFor<T>, ValueQuery>;
58

            
59
    #[pallet::genesis_config]
60
    pub struct GenesisConfig<T: Config> {
61
        pub _phantom_data: PhantomData<T>,
62
    }
63

            
64
    #[pallet::genesis_build]
65
    impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
66
        fn build(&self) {
67
            <OffchainWorkerTestEnabled<T>>::put(false);
68
        }
69
    }
70

            
71
    #[pallet::hooks]
72
    impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
73
        /// Offchain worker entry point.
74
        ///
75
        /// By implementing `fn offchain_worker` you declare a new offchain worker.
76
        /// This function will be called when the node is fully synced and a new best block is
77
        /// successfully imported.
78
        /// Note that it's not guaranteed for offchain workers to run on EVERY block, there might
79
        /// be cases where some blocks are skipped, or for some the worker runs twice (re-orgs),
80
        /// so the code should be able to handle that.
81
        fn offchain_worker(block_number: BlockNumberFor<T>) {
82
            log::info!("Entering off-chain worker.");
83
            // The entry point of your code called by off-chain worker
84
            let res = Self::send_raw_unsigned_transaction(block_number);
85
            if let Err(e) = res {
86
                log::error!("Error: {}", e);
87
            }
88
        }
89
    }
90
    #[pallet::call]
91
    impl<T: Config> Pallet<T> {
92
        /// Switches on or off the offchain worker
93
        ///
94
        /// Only root (or specified authority account) should be able to switch
95
        /// the off-chain worker on and off to avoid enabling it by default in production
96
        #[pallet::call_index(0)]
97
        #[pallet::weight(T::DbWeight::get().write)]
98
        #[allow(clippy::useless_conversion)]
99
        pub fn set_offchain_worker(
100
            origin: OriginFor<T>,
101
            is_testing_enabled: bool,
102
        ) -> DispatchResultWithPostInfo {
103
            ensure_root(origin)?;
104

            
105
            OffchainWorkerTestEnabled::<T>::put(is_testing_enabled);
106
            Ok(().into())
107
        }
108

            
109
        /// Submits unsigned transaction that emits an event
110
        ///
111
        /// Can be triggered only by an offchain worker
112
        #[pallet::call_index(1)]
113
        #[pallet::weight(T::DbWeight::get().write)]
114
        #[allow(clippy::useless_conversion)]
115
        pub fn submit_event_unsigned(
116
            origin: OriginFor<T>,
117
            _block_number: BlockNumberFor<T>,
118
        ) -> DispatchResultWithPostInfo {
119
            // This ensures that the function can only be called via unsigned transaction.
120
            ensure_none(origin)?;
121

            
122
            ensure!(
123
                OffchainWorkerTestEnabled::<T>::get(),
124
                Error::<T>::OffchainWorkerNotEnabled,
125
            );
126

            
127
            // Increment the block number at which we expect next unsigned transaction.
128
            let current_block = <frame_system::Pallet<T>>::block_number();
129

            
130
            // Emits offchain event
131
            Self::deposit_event(Event::SimpleOffchainEvent);
132

            
133
            <NextUnsignedAt<T>>::put(current_block + T::UnsignedInterval::get());
134
            Ok(().into())
135
        }
136
    }
137

            
138
    /// Events for the pallet.
139
    #[pallet::event]
140
    #[pallet::generate_deposit(pub(super) fn deposit_event)]
141
    pub enum Event<T: Config> {
142
        /// Simple offchain event
143
        SimpleOffchainEvent,
144
    }
145

            
146
    #[pallet::error]
147
    pub enum Error<T> {
148
        OffchainWorkerNotEnabled,
149
    }
150

            
151
    #[pallet::validate_unsigned]
152
    impl<T: Config> ValidateUnsigned for Pallet<T> {
153
        type Call = Call<T>;
154

            
155
        /// Validate unsigned call to this module.
156
        ///
157
        /// By default unsigned transactions are disallowed, but implementing the validator
158
        /// here we make sure that some particular calls (the ones produced by offchain worker)
159
        /// are being whitelisted and marked as valid.
160
        fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity {
161
            if let Call::submit_event_unsigned { block_number } = call {
162
                Self::validate_transaction_parameters(block_number)
163
            } else {
164
                InvalidTransaction::Call.into()
165
            }
166
        }
167
    }
168
}
169

            
170
impl<T: Config> Pallet<T> {
171
    /// A helper function to sign payload and send an unsigned transaction
172
    fn send_raw_unsigned_transaction(block_number: BlockNumberFor<T>) -> Result<(), &'static str> {
173
        // Make sure offchain worker testing is enabled
174
        let is_offchain_worker_enabled = OffchainWorkerTestEnabled::<T>::get();
175
        if !is_offchain_worker_enabled {
176
            return Err("Offchain worker is not enabled");
177
        }
178
        // Make sure transaction can be sent
179
        let next_unsigned_at = NextUnsignedAt::<T>::get();
180
        if next_unsigned_at > block_number {
181
            return Err("Too early to send unsigned transaction");
182
        }
183

            
184
        let call = Call::submit_event_unsigned { block_number };
185

            
186
        let xt = T::create_bare(call.into());
187
        SubmitTransaction::<T, Call<T>>::submit_transaction(xt)
188
            .map_err(|()| "Unable to submit unsigned transaction.")?;
189

            
190
        Ok(())
191
    }
192

            
193
    fn validate_transaction_parameters(block_number: &BlockNumberFor<T>) -> TransactionValidity {
194
        // Make sure offchain worker testing is enabled
195
        let is_offchain_worker_enabled = OffchainWorkerTestEnabled::<T>::get();
196
        if !is_offchain_worker_enabled {
197
            return InvalidTransaction::Call.into();
198
        }
199
        // Now let's check if the transaction has any chance to succeed.
200
        let next_unsigned_at = NextUnsignedAt::<T>::get();
201
        if &next_unsigned_at > block_number {
202
            return InvalidTransaction::Stale.into();
203
        }
204
        // Let's make sure to reject transactions from the future.
205
        let current_block = <system::Pallet<T>>::block_number();
206
        if &current_block < block_number {
207
            return InvalidTransaction::Future.into();
208
        }
209
        ValidTransaction::with_tag_prefix("ExampleOffchainWorker")
210
            // We set base priority to 2**20 and hope it's included before any other
211
            // transactions in the pool. Next we tweak the priority depending on how much
212
            // it differs from the current average. (the more it differs the more priority it
213
            // has).
214
            .priority(2u64.pow(20))
215
            // This transaction does not require anything else to go before into the pool.
216
            // In theory we could require `previous_unsigned_at` transaction to go first,
217
            // but it's not necessary in our case.
218
            //.and_requires()
219
            // We set the `provides` tag to be the same as `next_unsigned_at`. This makes
220
            // sure only one transaction produced after `next_unsigned_at` will ever
221
            // get to the transaction pool and will end up in the block.
222
            // We can still have multiple transactions compete for the same "spot",
223
            // and the one with higher priority will replace other one in the pool.
224
            .and_provides(next_unsigned_at)
225
            // The transaction is only valid for next 5 blocks. After that it's
226
            // going to be revalidated by the pool.
227
            .longevity(6)
228
            // It's fine to propagate that transaction to other peers, which means it can be
229
            // created even by nodes that don't produce blocks.
230
            // Note that sometimes it's better to keep it for yourself (if you are the block
231
            // producer), since for instance in some schemes others may copy your solution and
232
            // claim a reward.
233
            .propagate(true)
234
            .build()
235
    }
236
}