/
db.go
125 lines (104 loc) · 2.6 KB
/
db.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
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
package watcher
import (
"io/ioutil"
"log"
"os"
"path/filepath"
"sync"
sdk "github.com/okex/exchain/libs/cosmos-sdk/types"
"github.com/okex/exchain/libs/cosmos-sdk/client/flags"
dbm "github.com/okex/exchain/libs/tm-db"
evmtypes "github.com/okex/exchain/x/evm/types"
"github.com/spf13/viper"
)
const (
FlagFastQuery = "fast-query"
FlagFastQueryForWasm = "wasm-fast-query"
FlagFastQueryLru = "fast-lru"
FlagCheckWd = "check_watchdb"
WatchDbDir = "data"
WatchDBName = "watch"
)
type WatchStore struct {
db dbm.DB
params evmtypes.Params
paramsMutex sync.RWMutex
}
var gWatchStore *WatchStore = nil
var once sync.Once
func InstanceOfWatchStore() *WatchStore {
once.Do(func() {
if IsWatcherEnabled() {
gWatchStore = &WatchStore{db: initDb(), params: evmtypes.DefaultParams()}
}
})
return gWatchStore
}
func initDb() dbm.DB {
homeDir := viper.GetString(flags.FlagHome)
dbPath := filepath.Join(homeDir, WatchDbDir)
versionPath := filepath.Join(dbPath, WatchDBName+".db", "VERSION")
if !checkVersion(versionPath) {
os.RemoveAll(filepath.Join(dbPath, WatchDBName+".db"))
}
db, err := sdk.NewDB(WatchDBName, dbPath)
if err != nil {
panic(err)
}
writeVersion(versionPath)
return db
}
func checkVersion(versionPath string) bool {
content, err := ioutil.ReadFile(versionPath)
if err != nil || string(content) != version {
return false
}
return true
}
func writeVersion(versionPath string) {
ioutil.WriteFile(versionPath, []byte(version), 0666)
}
func (w WatchStore) Set(key []byte, value []byte) {
err := w.db.Set(key, value)
if err != nil {
log.Println("watchdb error: ", err.Error())
}
}
func (w WatchStore) Get(key []byte) ([]byte, error) {
return w.db.Get(key)
}
func (w WatchStore) GetUnsafe(key []byte, processor dbm.UnsafeValueProcessor) (interface{}, error) {
return w.db.GetUnsafeValue(key, processor)
}
func (w WatchStore) Delete(key []byte) {
err := w.db.Delete(key)
if err != nil {
log.Printf("watchdb error: " + err.Error())
}
}
func (w WatchStore) Has(key []byte) bool {
res, err := w.db.Has(key)
if err != nil {
log.Println("watchdb error: " + err.Error())
return false
}
return res
}
func (w WatchStore) Iterator(start, end []byte) dbm.Iterator {
it, err := w.db.Iterator(start, end)
if err != nil {
log.Println("watchdb error: " + err.Error())
return nil
}
return it
}
func (w WatchStore) GetEvmParams() evmtypes.Params {
w.paramsMutex.RLock()
defer w.paramsMutex.RUnlock()
return w.params
}
func (w *WatchStore) SetEvmParams(params evmtypes.Params) {
w.paramsMutex.Lock()
defer w.paramsMutex.Unlock()
w.params = params
}