mod.rs 8.77 KB
Newer Older
1
// Copyright 2018-2021 Parity Technologies (UK) Ltd.
2
3
4
5
6
7
8
9
10
11
12
13
14
//
// 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.

15
mod call_data;
16
17
#[cfg(feature = "ink-unstable-chain-extensions")]
mod chain_extension;
18
mod db;
19
mod hashing;
20
21
22
23
24
25
26
27
mod impls;
pub mod test_api;
mod typed_encoded;
mod types;

#[cfg(test)]
mod tests;

28
29
#[cfg(feature = "ink-unstable-chain-extensions")]
use self::chain_extension::ChainExtensionHandler;
30
31
32
33
pub use self::{
    call_data::CallData,
    db::{
        AccountError,
34
        EmittedEvent,
35
36
37
38
        PastPrints,
    },
    typed_encoded::TypedEncodedError,
};
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
use self::{
    db::{
        Account,
        AccountsDb,
        Block,
        ChainSpec,
        Console,
        EmittedEventsRecorder,
        ExecContext,
    },
    typed_encoded::TypedEncoded,
    types::{
        OffAccountId,
        OffBalance,
        OffBlockNumber,
        OffHash,
        OffTimestamp,
    },
};
use super::OnInstance;
59
use crate::Environment;
60
61
62
63
64
65
66
67
68
69
70
71
use core::cell::RefCell;
use derive_more::From;

#[derive(Debug, From, PartialEq, Eq)]
pub enum OffChainError {
    Account(AccountError),
    TypedEncoded(TypedEncodedError),
    #[from(ignore)]
    UninitializedBlocks,
    #[from(ignore)]
    UninitializedExecutionContext,
    #[from(ignore)]
Hero Bird's avatar
Hero Bird committed
72
    UnregisteredChainExtension,
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
}

pub type Result<T> = core::result::Result<T, OffChainError>;

/// The off-chain environment.
///
/// Mainly used for off-chain testing.
pub struct EnvInstance {
    /// The accounts database of the environment.
    accounts: AccountsDb,
    /// Current execution context and context.
    exec_context: Vec<ExecContext>,
    /// The general chain spec.
    chain_spec: ChainSpec,
    /// The blocks of the chain.
    blocks: Vec<Block>,
    /// The console to print debug contents.
    console: Console,
Hero Bird's avatar
Hero Bird committed
91
92
93
    /// Handler for registered chain extensions.
    #[cfg(feature = "ink-unstable-chain-extensions")]
    chain_extension_handler: ChainExtensionHandler,
94
95
    /// Emitted events recorder.
    emitted_events: EmittedEventsRecorder,
96
97
    /// Set to true to disable clearing storage
    clear_storage_disabled: bool,
98
99
100
101
102
103
104
105
106
107
108
}

impl EnvInstance {
    /// Creates a new uninitialized off-chain environment.
    pub fn uninitialized() -> Self {
        Self {
            accounts: AccountsDb::new(),
            exec_context: Vec::new(),
            chain_spec: ChainSpec::uninitialized(),
            blocks: Vec::new(),
            console: Console::new(),
Hero Bird's avatar
Hero Bird committed
109
110
            #[cfg(feature = "ink-unstable-chain-extensions")]
            chain_extension_handler: ChainExtensionHandler::new(),
111
            emitted_events: EmittedEventsRecorder::new(),
112
            clear_storage_disabled: false,
113
114
115
        }
    }

116
117
118
119
120
121
    /// Returns `true` if the off-chain environment is uninitialized.
    pub fn is_initialized(&self) -> bool {
        !self.exec_context.is_empty()
    }

    /// Either resets or initializes the off-chain environment to default values.
122
    pub fn initialize_or_reset_as_default<T>(&mut self) -> crate::Result<()>
123
    where
124
125
        T: Environment,
        <T as Environment>::AccountId: From<[u8; 32]>,
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
    {
        if self.is_initialized() {
            self.reset()
        }
        self.initialize_as_default::<T>()?;
        Ok(())
    }

    /// Resets the off-chain environment to unintialized state.
    pub fn reset(&mut self) {
        self.accounts.reset();
        self.exec_context.clear();
        self.chain_spec.reset();
        self.blocks.clear();
        self.console.reset();
Hero Bird's avatar
Hero Bird committed
141
142
        #[cfg(feature = "ink-unstable-chain-extensions")]
        self.chain_extension_handler.reset();
143
        self.emitted_events.reset();
144
        self.clear_storage_disabled = false;
145
146
    }

147
148
149
150
151
152
153
154
155
156
157
158
159
    /// Initializes the whole off-chain environment.
    ///
    /// # Note
    ///
    /// This is needed since we operate on a static instance that cannot be
    /// made generic over all environmental types and thus we are required to
    /// initialize it upon program start uninitialized which is why we have
    /// `TypedEncoded` wrappers.
    ///
    /// The off-chain environment requires to be initialized before every usage.
    ///
    /// This routine implements a default initialization that should be fine
    /// for most use cases.
160
    pub fn initialize_as_default<T>(&mut self) -> crate::Result<()>
161
    where
162
163
        T: Environment,
        <T as Environment>::AccountId: From<[u8; 32]>,
164
165
166
167
168
169
170
171
172
173
    {
        use core::ops::Div as _;
        use num_traits::{
            Bounded as _,
            Zero as _,
        };
        let default_accounts = test_api::default_accounts::<T>()?;
        // Alice has half of the maximum possible amount.
        self.accounts.add_user_account::<T>(
            default_accounts.alice.clone(),
174
            T::Balance::max_value().div(T::Balance::from(2u32)),
175
176
177
178
        );
        // Bob has half the balance that alice got.
        self.accounts.add_user_account::<T>(
            default_accounts.bob,
179
            T::Balance::max_value().div(T::Balance::from(4u32)),
180
181
182
183
184
185
186
187
188
189
190
191
        );
        // All other default accounts have zero balance.
        self.accounts
            .add_user_account::<T>(default_accounts.charlie, T::Balance::zero());
        self.accounts
            .add_user_account::<T>(default_accounts.django, T::Balance::zero());
        self.accounts
            .add_user_account::<T>(default_accounts.eve, T::Balance::zero());
        self.accounts
            .add_user_account::<T>(default_accounts.frank, T::Balance::zero());
        // Initialize our first block.
        self.blocks.push(Block::new::<T>(
192
193
            T::BlockNumber::from(0u32),
            T::Timestamp::from(0u32),
194
195
196
197
198
199
200
        ));
        // Initialize chain specification.
        self.chain_spec.initialize_as_default::<T>()?;
        // Initialize the called contract account.
        let contract_account_id = T::AccountId::from([0x07; 32]);
        self.accounts.add_contract_account::<T>(
            contract_account_id.clone(),
201
202
            T::Balance::from(0u32),
            T::Balance::from(20u32),
203
204
        );
        // Initialize the execution context for the first contract execution.
205
        use crate::call::Selector;
206
207
208
        // The below selector bytes are incorrect but since calling doesn't work
        // yet we do not have to fix this now.
        let selector_bytes_for_call = [0x00; 4];
209
210
211
212
        self.exec_context.push(
            ExecContext::build::<T>()
                .caller(default_accounts.alice)
                .callee(contract_account_id)
213
214
                .gas(T::Balance::from(500_000u32))
                .transferred_value(T::Balance::from(500u32))
215
                .call_data(CallData::new(Selector::new(selector_bytes_for_call)))
216
217
218
219
220
221
                .finish(),
        );
        Ok(())
    }

    /// Advances the chain by a single block.
222
    pub fn advance_block<T>(&mut self) -> crate::Result<()>
223
    where
224
        T: Environment,
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
    {
        let new_block_number = T::BlockNumber::from(self.blocks.len() as u32);
        let new_timestamp = self.current_block()?.timestamp::<T>()?
            + self.chain_spec.block_time::<T>()?;
        self.blocks
            .push(Block::new::<T>(new_block_number, new_timestamp));
        Ok(())
    }

    /// Returns the current execution context.
    fn exec_context(&self) -> Result<&ExecContext> {
        self.exec_context
            .last()
            .ok_or(OffChainError::UninitializedExecutionContext)
    }

    /// Returns the current execution context.
    fn exec_context_mut(&mut self) -> Result<&mut ExecContext> {
        self.exec_context
            .last_mut()
            .ok_or(OffChainError::UninitializedExecutionContext)
    }

    /// Returns the current block of the chain.
    fn current_block(&self) -> Result<&Block> {
        self.blocks.last().ok_or(OffChainError::UninitializedBlocks)
    }

    /// Returns a mutable reference to the current block of the chain.
    fn current_block_mut(&mut self) -> Result<&mut Block> {
        self.blocks
            .last_mut()
257
            .ok_or(OffChainError::UninitializedBlocks)
258
    }
259
260
261
262

    fn chain_spec_mut(&mut self) -> &mut ChainSpec {
        &mut self.chain_spec
    }
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
}

impl OnInstance for EnvInstance {
    fn on_instance<F, R>(f: F) -> R
    where
        F: FnOnce(&mut Self) -> R,
    {
        thread_local!(
            static INSTANCE: RefCell<EnvInstance> = RefCell::new(
                EnvInstance::uninitialized()
            )
        );
        INSTANCE.with(|instance| f(&mut instance.borrow_mut()))
    }
}