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
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0

use crate::DiemValidatorInterface;
use anyhow::{anyhow, Result};
use diem_config::config::RocksdbConfig;
use diem_types::{
    account_address::AccountAddress,
    account_state::AccountState,
    contract_event::EventWithProof,
    event::EventKey,
    transaction::{Transaction, Version},
};
use diemdb::DiemDB;
use std::{convert::TryFrom, path::Path, sync::Arc};
use storage_interface::{DbReader, Order};

pub struct DBDebuggerInterface(Arc<dyn DbReader>);

impl DBDebuggerInterface {
    pub fn open<P: AsRef<Path> + Clone>(db_root_path: P) -> Result<Self> {
        Ok(Self(Arc::new(DiemDB::open(
            db_root_path,
            true,
            None,
            RocksdbConfig::default(),
        )?)))
    }
}

impl DiemValidatorInterface for DBDebuggerInterface {
    fn get_account_state_by_version(
        &self,
        account: AccountAddress,
        version: Version,
    ) -> Result<Option<AccountState>> {
        self.0
            .get_account_state_with_proof_by_version(account, version)?
            .0
            .map(|s| AccountState::try_from(&s))
            .transpose()
    }

    fn get_events(
        &self,
        key: &EventKey,
        start_seq: u64,
        limit: u64,
    ) -> Result<Vec<EventWithProof>> {
        self.0
            .get_events_with_proofs(key, start_seq, Order::Ascending, limit, None)
    }
    fn get_committed_transactions(&self, start: Version, limit: u64) -> Result<Vec<Transaction>> {
        Ok(self
            .0
            .get_transactions(start, limit, self.get_latest_version()?, false)?
            .transactions)
    }

    fn get_latest_version(&self) -> Result<Version> {
        let (version, _) = self
            .0
            .get_latest_transaction_info_option()?
            .ok_or_else(|| anyhow!("DB doesn't have any transaction."))?;
        Ok(version)
    }

    fn get_version_by_account_sequence(
        &self,
        account: AccountAddress,
        seq: u64,
    ) -> Result<Option<Version>> {
        let ledger_version = self.get_latest_version()?;
        Ok(self
            .0
            .get_account_transaction(account, seq, false, ledger_version)?
            .map(|info| info.version))
    }
}