github.com/ethersphere/bee/v2@v2.2.0/pkg/keystore/mem/service.go (about) 1 // Copyright 2020 The Swarm Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package mem 6 7 import ( 8 "crypto/ecdsa" 9 "fmt" 10 "sync" 11 12 "github.com/ethersphere/bee/v2/pkg/keystore" 13 ) 14 15 var _ keystore.Service = (*Service)(nil) 16 17 // Service is the memory-based keystore.Service implementation. 18 // 19 // Keys are stored in an in-memory map, where the key is the name of the private 20 // key, and the value is the structure where the actual private key and 21 // the password are stored. 22 type Service struct { 23 m map[string]key 24 mu sync.RWMutex 25 } 26 27 // New creates new memory-based keystore.Service implementation. 28 func New() *Service { 29 return &Service{ 30 m: make(map[string]key), 31 } 32 } 33 34 func (s *Service) Exists(name string) (bool, error) { 35 s.mu.RLock() 36 defer s.mu.RUnlock() 37 _, ok := s.m[name] 38 return ok, nil 39 40 } 41 42 func (s *Service) SetKey(name, password string, edg keystore.EDG) (*ecdsa.PrivateKey, error) { 43 pk, err := edg.Generate() 44 if err != nil { 45 return nil, fmt.Errorf("generate key: %w", err) 46 } 47 s.mu.Lock() 48 defer s.mu.Unlock() 49 50 s.m[name] = key{ 51 pk: pk, 52 password: password, 53 } 54 55 return pk, nil 56 } 57 58 func (s *Service) Key(name, password string, edg keystore.EDG) (pk *ecdsa.PrivateKey, created bool, err error) { 59 s.mu.Lock() 60 defer s.mu.Unlock() 61 62 k, ok := s.m[name] 63 if !ok { 64 pk, err := edg.Generate() 65 if err != nil { 66 return nil, false, fmt.Errorf("generate key: %w", err) 67 } 68 69 s.m[name] = key{ 70 pk: pk, 71 password: password, 72 } 73 74 return pk, true, err 75 } 76 77 if k.password != password { 78 return nil, false, keystore.ErrInvalidPassword 79 } 80 81 return k.pk, created, nil 82 } 83 84 type key struct { 85 pk *ecdsa.PrivateKey 86 password string 87 }