github.com/fibonacci-chain/fbc@v0.0.0-20231124064014-c7636198c1e9/x/evm/watcher/db.go (about) 1 package watcher 2 3 import ( 4 "io/ioutil" 5 "log" 6 "os" 7 "path/filepath" 8 "sync" 9 10 sdk "github.com/fibonacci-chain/fbc/libs/cosmos-sdk/types" 11 12 "github.com/fibonacci-chain/fbc/libs/cosmos-sdk/client/flags" 13 dbm "github.com/fibonacci-chain/fbc/libs/tm-db" 14 evmtypes "github.com/fibonacci-chain/fbc/x/evm/types" 15 "github.com/spf13/viper" 16 ) 17 18 const ( 19 FlagFastQuery = "fast-query" 20 FlagFastQueryLru = "fast-lru" 21 FlagCheckWd = "check_watchdb" 22 23 WatchDbDir = "data" 24 WatchDBName = "watch" 25 ) 26 27 type WatchStore struct { 28 db dbm.DB 29 params evmtypes.Params 30 paramsMutex sync.RWMutex 31 } 32 33 var gWatchStore *WatchStore = nil 34 var once sync.Once 35 36 func InstanceOfWatchStore() *WatchStore { 37 once.Do(func() { 38 if IsWatcherEnabled() { 39 gWatchStore = &WatchStore{db: initDb(), params: evmtypes.DefaultParams()} 40 } 41 }) 42 return gWatchStore 43 } 44 45 func initDb() dbm.DB { 46 homeDir := viper.GetString(flags.FlagHome) 47 dbPath := filepath.Join(homeDir, WatchDbDir) 48 49 versionPath := filepath.Join(dbPath, WatchDBName+".db", "VERSION") 50 if !checkVersion(versionPath) { 51 os.RemoveAll(filepath.Join(dbPath, WatchDBName+".db")) 52 } 53 54 db, err := sdk.NewDB(WatchDBName, dbPath) 55 if err != nil { 56 panic(err) 57 } 58 writeVersion(versionPath) 59 return db 60 } 61 62 func checkVersion(versionPath string) bool { 63 content, err := ioutil.ReadFile(versionPath) 64 if err != nil || string(content) != version { 65 return false 66 } 67 return true 68 } 69 70 func writeVersion(versionPath string) { 71 ioutil.WriteFile(versionPath, []byte(version), 0666) 72 } 73 74 func (w WatchStore) Set(key []byte, value []byte) { 75 err := w.db.Set(key, value) 76 if err != nil { 77 log.Println("watchdb error: ", err.Error()) 78 } 79 } 80 81 func (w WatchStore) Get(key []byte) ([]byte, error) { 82 return w.db.Get(key) 83 } 84 85 func (w WatchStore) GetUnsafe(key []byte, processor dbm.UnsafeValueProcessor) (interface{}, error) { 86 return w.db.GetUnsafeValue(key, processor) 87 } 88 89 func (w WatchStore) Delete(key []byte) { 90 err := w.db.Delete(key) 91 if err != nil { 92 log.Printf("watchdb error: " + err.Error()) 93 } 94 } 95 96 func (w WatchStore) Has(key []byte) bool { 97 res, err := w.db.Has(key) 98 if err != nil { 99 log.Println("watchdb error: " + err.Error()) 100 return false 101 } 102 return res 103 } 104 105 func (w WatchStore) Iterator(start, end []byte) dbm.Iterator { 106 it, err := w.db.Iterator(start, end) 107 if err != nil { 108 log.Println("watchdb error: " + err.Error()) 109 return nil 110 } 111 return it 112 } 113 114 func (w WatchStore) GetEvmParams() evmtypes.Params { 115 w.paramsMutex.RLock() 116 defer w.paramsMutex.RUnlock() 117 return w.params 118 } 119 120 func (w *WatchStore) SetEvmParams(params evmtypes.Params) { 121 w.paramsMutex.Lock() 122 defer w.paramsMutex.Unlock() 123 w.params = params 124 }