/
files.go
59 lines (48 loc) · 1.26 KB
/
files.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
package valkeystore
import (
"errors"
"os"
"path"
"github.com/ethereum/go-ethereum/common"
"github.com/corex-mn/go-corex/inter/validatorpk"
"github.com/corex-mn/go-corex/valkeystore/encryption"
)
var (
ErrNotFound = errors.New("key is not found")
ErrAlreadyExists = errors.New("key already exists")
)
type FileKeystore struct {
enc *encryption.Keystore
dir string
}
func NewFileKeystore(dir string, enc *encryption.Keystore) *FileKeystore {
return &FileKeystore{
enc: enc,
dir: dir,
}
}
func (f *FileKeystore) Has(pubkey validatorpk.PubKey) bool {
return fileExists(f.PathOf(pubkey))
}
func (f *FileKeystore) Add(pubkey validatorpk.PubKey, key []byte, auth string) error {
if f.Has(pubkey) {
return ErrAlreadyExists
}
return f.enc.StoreKey(f.PathOf(pubkey), pubkey, key, auth)
}
func (f *FileKeystore) Get(pubkey validatorpk.PubKey, auth string) (*encryption.PrivateKey, error) {
if !f.Has(pubkey) {
return nil, ErrNotFound
}
return f.enc.ReadKey(pubkey, f.PathOf(pubkey), auth)
}
func (f *FileKeystore) PathOf(pubkey validatorpk.PubKey) string {
return path.Join(f.dir, common.Bytes2Hex(pubkey.Bytes()))
}
func fileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}