-
Notifications
You must be signed in to change notification settings - Fork 2
/
instance.go
87 lines (73 loc) · 2.42 KB
/
instance.go
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
package mpt
import (
"encoding/binary"
"path/filepath"
"sync"
ethcmn "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/rawdb"
ethstate "github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/trie"
"github.com/fibonacci-chain/fbc/libs/cosmos-sdk/client/flags"
"github.com/fibonacci-chain/fbc/libs/cosmos-sdk/store/mpt/types"
sdk "github.com/fibonacci-chain/fbc/libs/cosmos-sdk/types"
"github.com/spf13/viper"
)
const (
mptDataDir = "data"
mptSpace = "mpt"
)
var (
gMptDatabase ethstate.Database = nil
initMptOnce sync.Once
)
func InstanceOfMptStore() ethstate.Database {
initMptOnce.Do(func() {
homeDir := viper.GetString(flags.FlagHome)
path := filepath.Join(homeDir, mptDataDir)
backend := viper.GetString(sdk.FlagDBBackend)
if backend == "" {
backend = string(types.GoLevelDBBackend)
}
kvstore, e := types.CreateKvDB(mptSpace, types.BackendType(backend), path)
if e != nil {
panic("fail to open database: " + e.Error())
}
db := rawdb.NewDatabase(kvstore)
gMptDatabase = ethstate.NewDatabaseWithConfig(db, &trie.Config{
Cache: int(TrieCacheSize),
Journal: "",
Preimages: true,
})
})
return gMptDatabase
}
// GetLatestStoredBlockHeight get latest mpt storage height
func (ms *MptStore) GetLatestStoredBlockHeight() uint64 {
rst, err := ms.db.TrieDB().DiskDB().Get(KeyPrefixAccLatestStoredHeight)
if err != nil || len(rst) == 0 {
return 0
}
return binary.BigEndian.Uint64(rst)
}
// SetLatestStoredBlockHeight sets the latest stored storage height
func (ms *MptStore) SetLatestStoredBlockHeight(height uint64) {
hhash := sdk.Uint64ToBigEndian(height)
ms.db.TrieDB().DiskDB().Put(KeyPrefixAccLatestStoredHeight, hhash)
}
// GetMptRootHash gets root mpt hash from block height
func (ms *MptStore) GetMptRootHash(height uint64) ethcmn.Hash {
hhash := sdk.Uint64ToBigEndian(height)
rst, err := ms.db.TrieDB().DiskDB().Get(append(KeyPrefixAccRootMptHash, hhash...))
if err != nil || len(rst) == 0 {
return ethcmn.Hash{}
}
return ethcmn.BytesToHash(rst)
}
// SetMptRootHash sets the mapping from block height to root mpt hash
func (ms *MptStore) SetMptRootHash(height uint64, hash ethcmn.Hash) {
hhash := sdk.Uint64ToBigEndian(height)
ms.db.TrieDB().DiskDB().Put(append(KeyPrefixAccRootMptHash, hhash...), hash.Bytes())
}
func (ms *MptStore) HasVersion(height int64) bool {
return ms.GetMptRootHash(uint64(height)) != ethcmn.Hash{}
}