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
// Copyright (c) Aptos
// SPDX-License-Identifier: Apache-2.0

//! This module provides mock dbreader for tests.

use crate::{DbReader, DbWriter};
use anyhow::{anyhow, Result};
use aptos_crypto::HashValue;
use aptos_types::{
    account_address::AccountAddress,
    account_config::AccountResource,
    account_state::AccountState,
    proof::SparseMerkleProof,
    state_store::{state_key::StateKey, state_value::StateValue},
    transaction::Version,
};
use move_deps::move_core_types::move_resource::MoveResource;

/// This is a mock of the DbReaderWriter in tests.
pub struct MockDbReaderWriter;

impl DbReader for MockDbReaderWriter {
    fn get_latest_state_value(&self, state_key: StateKey) -> Result<Option<StateValue>> {
        match state_key {
            StateKey::AccessPath(access_path) => {
                let account_state = get_mock_account_state();
                Ok(account_state
                    .get(&access_path.path)
                    .cloned()
                    .map(StateValue::from))
            }
            StateKey::Raw(raw_key) => Ok(Some(StateValue::from(raw_key))),
            _ => Err(anyhow!("Not supported state key type {:?}", state_key)),
        }
    }

    fn get_latest_version_option(&self) -> Result<Option<Version>> {
        // return a dummy version for tests
        Ok(Some(1))
    }

    fn get_latest_state_snapshot(&self) -> Result<Option<(Version, HashValue)>> {
        // return a dummy version for tests
        Ok(Some((1, HashValue::zero())))
    }

    fn get_state_value_by_version(
        &self,
        state_key: &StateKey,
        _: Version,
    ) -> Result<Option<StateValue>> {
        // dummy proof which is not used
        Ok(self.get_latest_state_value(state_key.clone()).unwrap())
    }

    fn get_state_proof_by_version(
        &self,
        _state_key: &StateKey,
        _version: Version,
    ) -> Result<SparseMerkleProof> {
        Ok(SparseMerkleProof::new(None, vec![]))
    }
}

fn get_mock_account_state() -> AccountState {
    let account_resource = AccountResource::new(0, vec![], AccountAddress::random());

    let mut account_state = AccountState::default();
    account_state.insert(
        AccountResource::resource_path(),
        bcs::to_bytes(&account_resource).unwrap(),
    );
    account_state
}

impl DbWriter for MockDbReaderWriter {}