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::{
19
    self as system, ensure_none, ensure_root, offchain::SubmitTransaction,
20
    pallet_prelude::BlockNumberFor,
21
};
22
use sp_runtime::transaction_validity::{InvalidTransaction, TransactionValidity, ValidTransaction};
23

            
24
pub use pallet::*;
25
#[frame_support::pallet]
26
pub mod pallet {
27
    use super::*;
28
    use frame_support::pallet_prelude::*;
29
    use frame_system::pallet_prelude::*;
30

            
31
178
    #[pallet::pallet]
32
    pub struct Pallet<T>(_);
33

            
34
    #[pallet::config]
35
    pub trait Config:
36
        frame_system::offchain::SendTransactionTypes<Call<Self>> + frame_system::Config
37
    {
38
        /// The overarching event type.
39
        type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
40

            
41
        /// Number of blocks of cooldown after unsigned transaction is included.
42
        ///
43
        /// This ensures that we only accept unsigned transactions once, every `UnsignedInterval`
44
        /// blocks.
45
        #[pallet::constant]
46
        type UnsignedInterval: Get<BlockNumberFor<Self>>;
47
    }
48

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
185
        SubmitTransaction::<T, Call<T>>::submit_unsigned_transaction(call.into())
186
            .map_err(|()| "Unable to submit unsigned transaction.")?;
187

            
188
        Ok(())
189
    }
190

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