pchain-runtime 0.4.3

parallelchain-runtime: ParallelChain Mainnet Runtime for state transition in ParallelChain Mainnet
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
/*
    Copyright © 2023, ParallelChain Lab
    Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0
*/

//! Defines a struct that serves as a cache layer on top of World State.
//!
//! There are two data caches:
//! - `reads` (first-hand data obtained from world state)
//! - `writes` (the data pended to commit to world state)
//!
//! The cache layer also measures gas consumption for the read-write operations.
//!
//! In Read Operation, `writes` is accessed first. If data is not found, search `reads`. If it fails in both Sets,
//! then finally World State is accessed. The result will then be cached to `reads`.
//!
//! In Write Operation, it first performs a Read Operation, and then updates the `writes` with the newest data.
//!
//! At the end of state transition, if it succeeds, the data in `writes` will be committed to World State. Otherwise,
//! `writes` is discarded without any changes to World State.

use std::{cell::RefCell, collections::HashMap};

use pchain_types::cryptography::PublicAddress;
use pchain_world_state::{
    keys::AppKey,
    states::{AccountStorageState, WorldState},
    storage::WorldStateStorage,
};
use wasmer::Store;

use crate::{
    contract::{self, Module, SmartContractContext},
    cost::CostChange,
    gas,
};

/// ReadWriteSet defines data cache for Read-Write opertaions during state transition.
#[derive(Clone)]
pub(crate) struct ReadWriteSet<S>
where
    S: WorldStateStorage + Send + Sync + Clone,
{
    /// World State services as the data source
    pub ws: WorldState<S>,
    /// writes stores key-value pairs for Write operations. It stores the data that is pending to store into world state
    pub writes: HashMap<CacheKey, CacheValue>,
    /// reads stores key-value pairs from Read operations. It is de facto the original data read from world state.
    pub reads: RefCell<HashMap<CacheKey, Option<CacheValue>>>,
    /// write_gas is protocol defined cost that to-be-charged write operation has been executed
    pub write_gas: CostChange,
    /// read_gas is protocol defined cost that to-be-charged read operation has been executed
    pub read_gas: RefCell<CostChange>,
}

impl<S> ReadWriteSet<S>
where
    S: WorldStateStorage + Send + Sync + Clone,
{
    pub fn new(ws: WorldState<S>) -> Self {
        Self {
            ws,
            writes: HashMap::new(),
            reads: RefCell::new(HashMap::new()),
            write_gas: CostChange::default(),
            read_gas: RefCell::new(CostChange::default()),
        }
    }

    /// get the balance from readwrite set. It key is not found, then get from world state and then cache it.
    pub fn balance(&self, address: PublicAddress) -> (u64, CostChange) {
        match self.get(CacheKey::Balance(address)) {
            (Some(CacheValue::Balance(value)), cost) => (value, cost),
            _ => panic!(),
        }
    }

    /// set balance to write set. This operation does not write to world state immediately
    pub fn set_balance(&mut self, address: PublicAddress, balance: u64) -> CostChange {
        self.set(CacheKey::Balance(address), CacheValue::Balance(balance))
    }

    /// remove cached writes and return the value
    pub fn purge_balance(&mut self, address: PublicAddress) -> u64 {
        let (balance, _) = self.balance(address);
        let key = CacheKey::Balance(address);
        self.writes.remove(&key);
        balance
    }

    /// get the contract code from readwrite set. It key is not found, then get from world state and then cache it.
    pub fn code(&self, address: PublicAddress) -> (Option<Vec<u8>>, CostChange) {
        match self.get(CacheKey::ContractCode(address)) {
            (Some(CacheValue::ContractCode(value)), cost) => (Some(value), cost),
            (None, cost) => (None, cost),
            _ => panic!(),
        }
    }

    /// get the contract code from smart contract cache. It it is not found, then get from read write set, i.e. code()
    pub fn code_from_sc_cache(
        &self,
        address: PublicAddress,
        sc_context: &SmartContractContext,
    ) -> (Option<(Module, Store)>, CostChange) {
        let wasmer_store = sc_context.instantiate_store();
        let cached_module = match &sc_context.cache {
            Some(sc_cache) => contract::Module::from_cache(address, sc_cache, &wasmer_store),
            None => None,
        };

        // found from Smart Contract Cache
        if let Some(module) = cached_module {
            let cost_change = CostChange::deduct(gas::get_code_cost(module.bytes_length()));
            *self.read_gas.borrow_mut() += cost_change;
            return (Some((module, wasmer_store)), cost_change);
        }

        // found from read write set or world state
        let (bytes, cost_change) = self.code(address);
        let contract_code = match bytes {
            Some(bs) => bs,
            None => return (None, cost_change),
        };

        // build module
        let module = match contract::Module::from_wasm_bytecode_unchecked(
            contract::CBI_VERSION,
            &contract_code,
            &wasmer_store,
        ) {
            Ok(module) => {
                // cache to sc_cache
                if let Some(sc_cache) = &sc_context.cache {
                    module.cache_to(address, &mut sc_cache.clone());
                }
                module
            }
            Err(_) => return (None, cost_change),
        };

        (Some((module, wasmer_store)), cost_change)
    }

    /// set contract bytecode. This operation does not write to world state immediately
    pub fn set_code(&mut self, address: PublicAddress, code: Vec<u8>) -> CostChange {
        self.set(
            CacheKey::ContractCode(address),
            CacheValue::ContractCode(code),
        )
    }

    /// get the CBI version of the contract
    pub fn cbi_version(&self, address: PublicAddress) -> (Option<u32>, CostChange) {
        match self.get(CacheKey::CBIVersion(address)) {
            (Some(CacheValue::CBIVersion(value)), cost) => (Some(value), cost),
            (None, cost) => (None, cost),
            _ => panic!(),
        }
    }

    /// set cbi version. This operation does not write to world state immediately
    pub fn set_cbi_version(&mut self, address: PublicAddress, cbi_version: u32) -> CostChange {
        self.set(
            CacheKey::CBIVersion(address),
            CacheValue::CBIVersion(cbi_version),
        )
    }

    /// get the contract storage from readwrite set. It key is not found, then get from world state and then cache it.
    pub fn app_data(
        &self,
        address: PublicAddress,
        app_key: AppKey,
    ) -> (Option<Vec<u8>>, CostChange) {
        match self.get(CacheKey::App(address, app_key)) {
            (Some(CacheValue::App(value)), cost) => {
                if value.is_empty() {
                    (None, cost)
                } else {
                    (Some(value), cost)
                }
            }
            (None, cost) => (None, cost),
            _ => panic!(),
        }
    }

    /// set value to contract storage. This operation does not write to world state immediately
    pub fn set_app_data(
        &mut self,
        address: PublicAddress,
        app_key: AppKey,
        value: Vec<u8>,
    ) -> CostChange {
        self.set(CacheKey::App(address, app_key), CacheValue::App(value))
    }

    /// set value to contract storage. This operation does not write to world state immediately.
    /// It is gas-free operation.
    pub fn set_app_data_uncharged(
        &mut self,
        address: PublicAddress,
        app_key: AppKey,
        value: Vec<u8>,
    ) {
        self.writes
            .insert(CacheKey::App(address, app_key), CacheValue::App(value));
    }

    /// check if App Key already exists
    pub fn contains_app_data(&self, address: PublicAddress, app_key: AppKey) -> bool {
        let cache_key = CacheKey::App(address, app_key.clone());

        // charge gas for contains and charge gas
        *self.read_gas.borrow_mut() += CostChange::deduct(gas::contains_cost(cache_key.len()));

        // check from the value that was previously written/read
        self.writes
            .get(&cache_key)
            .filter(|v| v.len() != 0)
            .is_some()
            || self
                .reads
                .borrow()
                .get(&cache_key)
                .filter(|v| v.is_some())
                .is_some()
            || self.ws.contains().storage_value(&address, &app_key)
    }

    /// check if App Key already exists. It is gas-free operation.
    pub fn contains_app_data_from_account_storage_state(
        &self,
        account_storage_state: &AccountStorageState<S>,
        app_key: AppKey,
    ) -> bool {
        let address = account_storage_state.address();
        let cache_key = CacheKey::App(address, app_key.clone());

        // check from the value that was previously written/read
        self.writes
            .get(&cache_key)
            .filter(|v| v.len() != 0)
            .is_some()
            || self
                .reads
                .borrow()
                .get(&cache_key)
                .filter(|v| v.is_some())
                .is_some()
            || self
                .ws
                .contains()
                .storage_value_from_account_storage_state(account_storage_state, &app_key)
    }

    /// Get app data given a account storage state. It is gas-free operation.
    pub fn app_data_from_account_storage_state(
        &self,
        account_storage_state: &AccountStorageState<S>,
        app_key: AppKey,
    ) -> Option<Vec<u8>> {
        let address = account_storage_state.address();
        let cache_key = CacheKey::App(address, app_key.clone());

        match self.writes.get(&cache_key) {
            Some(CacheValue::App(value)) => return Some(value.clone()),
            Some(_) => panic!(),
            None => {}
        }

        match self.reads.borrow().get(&cache_key) {
            Some(Some(CacheValue::App(value))) => return Some(value.clone()),
            Some(None) => return None,
            Some(_) => panic!(),
            None => {}
        }

        self.ws
            .cached_get()
            .storage_value(account_storage_state.address(), &app_key)
            .or_else(|| account_storage_state.get(&app_key))
    }

    /// Lowest level of get operation. It gets latest value from readwrite set. It key is not found, then get from world state and then cache it.
    fn get(&self, key: CacheKey) -> (Option<CacheValue>, CostChange) {
        // 1. Return the value that was written earlier in the transaction ('read-your-write' semantics).
        if let Some(value) = self.writes.get(&key) {
            let cost_change = self.charge_read_cost(&key, Some(value));
            return (Some(value.clone()), cost_change);
        }

        // 2. Return the value that was read eariler in the transaction
        if let Some(value) = self.reads.borrow().get(&key) {
            let cost_change = self.charge_read_cost(&key, value.as_ref());
            return (value.clone(), cost_change);
        }

        // 3. Get the value from world state
        let value = key.get_from_world_state(&self.ws);
        let cost_change = self.charge_read_cost(&key, value.as_ref());

        // 4. Cache to reads
        self.reads.borrow_mut().insert(key, value.clone());

        (value, cost_change)
    }

    /// lowest level of set operation. It inserts to Write Set and returns the gas cost for this set operation.
    fn set(&mut self, key: CacheKey, value: CacheValue) -> CostChange {
        let key_len = key.len();
        let new_val_len = value.len();

        // 1. Get the length of original value and Charge for read cost
        let old_val_len = self.get(key.clone()).0.map_or(0, |v| v.len());

        // 2. Insert to write set
        self.writes.insert(key, value);

        // 3. Calculate gas cost
        self.charge_write_cost(key_len, old_val_len, new_val_len)
    }

    fn charge_read_cost(&self, key: &CacheKey, value: Option<&CacheValue>) -> CostChange {
        let cost_change = match key {
            CacheKey::ContractCode(_) => {
                CostChange::deduct(gas::get_code_cost(value.as_ref().map_or(0, |v| v.len())))
            }
            _ => CostChange::deduct(gas::get_cost(
                key.len(),
                value.as_ref().map_or(0, |v| v.len()),
            )),
        };
        *self.read_gas.borrow_mut() += cost_change;
        cost_change
    }

    fn charge_write_cost(
        &mut self,
        key_len: usize,
        old_val_len: usize,
        new_val_len: usize,
    ) -> CostChange {
        let new_cost_change =
            // old_val_len is obtained from Get so the cost of reading the key is already charged
            CostChange::reward(gas::set_cost_delete_old_value(key_len, old_val_len, new_val_len)) +
            CostChange::deduct(gas::set_cost_write_new_value(new_val_len)) +
            CostChange::deduct(gas::set_cost_rehash(key_len));
        self.write_gas += new_cost_change;
        new_cost_change
    }

    pub fn commit_to_world_state(self) -> WorldState<S> {
        let mut ws = self.ws;
        // apply changes to world state
        self.writes.into_iter().for_each(|(cache_key, new_value)| {
            new_value.set_to_world_state(cache_key, &mut ws);
        });
        ws.commit();
        ws
    }
}

/// CacheKey is the key for state changes cache in Runtime. It is different with world state Key or App Key for
/// being useful in:
/// - data read write cache
/// - components in gas cost calculation
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub(crate) enum CacheKey {
    App(PublicAddress, AppKey),
    Balance(PublicAddress),
    ContractCode(PublicAddress),
    CBIVersion(PublicAddress),
}

impl CacheKey {
    /// length of the value as an input to gas calculation
    pub fn len(&self) -> usize {
        match self {
            CacheKey::App(address, key) => {
                gas::ACCOUNT_STATE_KEY_LENGTH + address.len() + key.len()
            }
            CacheKey::Balance(_) | CacheKey::ContractCode(_) | CacheKey::CBIVersion(_) => {
                gas::ACCOUNT_STATE_KEY_LENGTH
            }
        }
    }

    /// get_from_world_state gets value from world state according to CacheKey
    fn get_from_world_state<S>(&self, ws: &WorldState<S>) -> Option<CacheValue>
    where
        S: WorldStateStorage + Send + Sync + Clone,
    {
        match &self {
            CacheKey::App(address, app_key) => {
                ws.storage_value(address, app_key).map(CacheValue::App)
            }
            CacheKey::Balance(address) => Some(CacheValue::Balance(ws.balance(address.to_owned()))),
            CacheKey::ContractCode(address) => {
                ws.code(address.to_owned()).map(CacheValue::ContractCode)
            }
            CacheKey::CBIVersion(address) => ws
                .cbi_version(address.to_owned())
                .map(CacheValue::CBIVersion),
        }
    }
}

/// CacheValue is the cached write operations that are pending to be applied to world state.
/// It is used as
/// - intermediate data which could be dropped later.
/// - write information for gas calculation
#[derive(Clone, Debug)]
pub(crate) enum CacheValue {
    App(Vec<u8>),
    Balance(u64),
    ContractCode(Vec<u8>),
    CBIVersion(u32),
}

impl CacheValue {
    /// length of the value as an input to gas calculation
    pub fn len(&self) -> usize {
        match self {
            CacheValue::App(value) => value.len(),
            CacheValue::Balance(balance) => std::mem::size_of_val(balance),
            CacheValue::ContractCode(code) => code.len(),
            CacheValue::CBIVersion(cbi_version) => std::mem::size_of_val(cbi_version),
        }
    }

    /// set_all_to_world_state performs setting cache values to world state according to CacheKey
    fn set_to_world_state<S>(self, key: CacheKey, ws: &mut WorldState<S>)
    where
        S: WorldStateStorage + Send + Sync + Clone,
    {
        match self {
            CacheValue::App(value) => {
                if let CacheKey::App(address, app_key) = key {
                    ws.cached().set_storage_value(address, app_key, value);
                }
            }
            CacheValue::Balance(value) => {
                if let CacheKey::Balance(address) = key {
                    ws.cached().set_balance(address, value);
                }
            }
            CacheValue::ContractCode(value) => {
                if let CacheKey::ContractCode(address) = key {
                    ws.cached().set_code(address, value);
                }
            }
            CacheValue::CBIVersion(value) => {
                if let CacheKey::CBIVersion(address) = key {
                    ws.cached().set_cbi_version(address, value);
                }
            }
        }
    }
}