github.com/unicornultrafoundation/go-u2u@v1.0.0-rc1.0.20240205080301-e74a83d3fadc/valkeystore/cache.go (about) 1 package valkeystore 2 3 import ( 4 "errors" 5 6 "github.com/unicornultrafoundation/go-u2u/native/validatorpk" 7 "github.com/unicornultrafoundation/go-u2u/valkeystore/encryption" 8 ) 9 10 var ( 11 ErrAlreadyUnlocked = errors.New("already unlocked") 12 ErrLocked = errors.New("key is locked") 13 ) 14 15 type CachedKeystore struct { 16 backend RawKeystoreI 17 cache map[string]*encryption.PrivateKey 18 } 19 20 func NewCachedKeystore(backend RawKeystoreI) *CachedKeystore { 21 return &CachedKeystore{ 22 backend: backend, 23 cache: make(map[string]*encryption.PrivateKey), 24 } 25 } 26 27 func (c *CachedKeystore) Unlocked(pubkey validatorpk.PubKey) bool { 28 _, ok := c.cache[c.idxOf(pubkey)] 29 return ok 30 } 31 32 func (c *CachedKeystore) Has(pubkey validatorpk.PubKey) bool { 33 if c.Unlocked(pubkey) { 34 return true 35 } 36 return c.backend.Has(pubkey) 37 } 38 39 func (c *CachedKeystore) Unlock(pubkey validatorpk.PubKey, auth string) error { 40 if c.Unlocked(pubkey) { 41 return ErrAlreadyUnlocked 42 } 43 key, err := c.backend.Get(pubkey, auth) 44 if err != nil { 45 return err 46 } 47 c.cache[c.idxOf(pubkey)] = key 48 return nil 49 } 50 51 func (c *CachedKeystore) GetUnlocked(pubkey validatorpk.PubKey) (*encryption.PrivateKey, error) { 52 if !c.Unlocked(pubkey) { 53 return nil, ErrLocked 54 } 55 return c.cache[c.idxOf(pubkey)], nil 56 } 57 58 func (c *CachedKeystore) idxOf(pubkey validatorpk.PubKey) string { 59 return string(pubkey.Bytes()) 60 } 61 62 func (c *CachedKeystore) Add(pubkey validatorpk.PubKey, key []byte, auth string) error { 63 return c.backend.Add(pubkey, key, auth) 64 } 65 66 func (c *CachedKeystore) Get(pubkey validatorpk.PubKey, auth string) (*encryption.PrivateKey, error) { 67 return c.backend.Get(pubkey, auth) 68 }