-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
68 lines (56 loc) · 1.57 KB
/
cache.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
package valkeystore
import (
"errors"
"github.com/corex-mn/go-corex/inter/validatorpk"
"github.com/corex-mn/go-corex/valkeystore/encryption"
)
var (
ErrAlreadyUnlocked = errors.New("already unlocked")
ErrLocked = errors.New("key is locked")
)
type CachedKeystore struct {
backend RawKeystoreI
cache map[string]*encryption.PrivateKey
}
func NewCachedKeystore(backend RawKeystoreI) *CachedKeystore {
return &CachedKeystore{
backend: backend,
cache: make(map[string]*encryption.PrivateKey),
}
}
func (c *CachedKeystore) Unlocked(pubkey validatorpk.PubKey) bool {
_, ok := c.cache[c.idxOf(pubkey)]
return ok
}
func (c *CachedKeystore) Has(pubkey validatorpk.PubKey) bool {
if c.Unlocked(pubkey) {
return true
}
return c.backend.Has(pubkey)
}
func (c *CachedKeystore) Unlock(pubkey validatorpk.PubKey, auth string) error {
if c.Unlocked(pubkey) {
return ErrAlreadyUnlocked
}
key, err := c.backend.Get(pubkey, auth)
if err != nil {
return err
}
c.cache[c.idxOf(pubkey)] = key
return nil
}
func (c *CachedKeystore) GetUnlocked(pubkey validatorpk.PubKey) (*encryption.PrivateKey, error) {
if !c.Unlocked(pubkey) {
return nil, ErrLocked
}
return c.cache[c.idxOf(pubkey)], nil
}
func (c *CachedKeystore) idxOf(pubkey validatorpk.PubKey) string {
return string(pubkey.Bytes())
}
func (c *CachedKeystore) Add(pubkey validatorpk.PubKey, key []byte, auth string) error {
return c.backend.Add(pubkey, key, auth)
}
func (c *CachedKeystore) Get(pubkey validatorpk.PubKey, auth string) (*encryption.PrivateKey, error) {
return c.backend.Get(pubkey, auth)
}