github.com/unicornultrafoundation/go-u2u@v1.0.0-rc1.0.20240205080301-e74a83d3fadc/valkeystore/files.go (about) 1 package valkeystore 2 3 import ( 4 "errors" 5 "os" 6 "path" 7 8 "github.com/unicornultrafoundation/go-u2u/common" 9 10 "github.com/unicornultrafoundation/go-u2u/native/validatorpk" 11 "github.com/unicornultrafoundation/go-u2u/valkeystore/encryption" 12 ) 13 14 var ( 15 ErrNotFound = errors.New("key is not found") 16 ErrAlreadyExists = errors.New("key already exists") 17 ) 18 19 type FileKeystore struct { 20 enc *encryption.Keystore 21 dir string 22 } 23 24 func NewFileKeystore(dir string, enc *encryption.Keystore) *FileKeystore { 25 return &FileKeystore{ 26 enc: enc, 27 dir: dir, 28 } 29 } 30 31 func (f *FileKeystore) Has(pubkey validatorpk.PubKey) bool { 32 return fileExists(f.PathOf(pubkey)) 33 } 34 35 func (f *FileKeystore) Add(pubkey validatorpk.PubKey, key []byte, auth string) error { 36 if f.Has(pubkey) { 37 return ErrAlreadyExists 38 } 39 return f.enc.StoreKey(f.PathOf(pubkey), pubkey, key, auth) 40 } 41 42 func (f *FileKeystore) Get(pubkey validatorpk.PubKey, auth string) (*encryption.PrivateKey, error) { 43 if !f.Has(pubkey) { 44 return nil, ErrNotFound 45 } 46 return f.enc.ReadKey(pubkey, f.PathOf(pubkey), auth) 47 } 48 49 func (f *FileKeystore) PathOf(pubkey validatorpk.PubKey) string { 50 return path.Join(f.dir, common.Bytes2Hex(pubkey.Bytes())) 51 } 52 53 func fileExists(filename string) bool { 54 info, err := os.Stat(filename) 55 if err != nil { 56 return false 57 } 58 return !info.IsDir() 59 }