github.com/unicornultrafoundation/go-u2u@v1.0.0-rc1.0.20240205080301-e74a83d3fadc/valkeystore/mem.go (about) 1 package valkeystore 2 3 import ( 4 "errors" 5 6 "github.com/unicornultrafoundation/go-u2u/crypto" 7 8 "github.com/unicornultrafoundation/go-u2u/native/validatorpk" 9 "github.com/unicornultrafoundation/go-u2u/valkeystore/encryption" 10 ) 11 12 type MemKeystore struct { 13 mem map[string]*encryption.PrivateKey 14 auth map[string]string 15 } 16 17 func NewMemKeystore() *MemKeystore { 18 return &MemKeystore{ 19 mem: make(map[string]*encryption.PrivateKey), 20 auth: make(map[string]string), 21 } 22 } 23 24 func (m *MemKeystore) Has(pubkey validatorpk.PubKey) bool { 25 _, ok := m.mem[m.idxOf(pubkey)] 26 return ok 27 } 28 29 func (m *MemKeystore) Add(pubkey validatorpk.PubKey, key []byte, auth string) error { 30 if m.Has(pubkey) { 31 return ErrAlreadyExists 32 } 33 if pubkey.Type != validatorpk.Types.Secp256k1 { 34 return encryption.ErrNotSupportedType 35 } 36 decoded, err := crypto.ToECDSA(key) 37 if err != nil { 38 return err 39 } 40 m.mem[m.idxOf(pubkey)] = &encryption.PrivateKey{ 41 Type: pubkey.Type, 42 Bytes: key, 43 Decoded: decoded, 44 } 45 m.auth[m.idxOf(pubkey)] = auth 46 return nil 47 } 48 49 func (m *MemKeystore) Get(pubkey validatorpk.PubKey, auth string) (*encryption.PrivateKey, error) { 50 if !m.Has(pubkey) { 51 return nil, ErrNotFound 52 } 53 if m.auth[m.idxOf(pubkey)] != auth { 54 return nil, errors.New("could not decrypt key with given password") 55 } 56 return m.mem[m.idxOf(pubkey)], nil 57 } 58 59 func (m *MemKeystore) idxOf(pubkey validatorpk.PubKey) string { 60 return string(pubkey.Bytes()) 61 }