You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
1.7 KiB

  1. /*
  2. package memstorage provides a simple in-memory key store designed for
  3. use in test cases, particularly to isolate them from the filesystem,
  4. concurrency, and cleanup issues.
  5. */
  6. package memstorage
  7. import (
  8. "github.com/pkg/errors"
  9. keys "github.com/tendermint/go-crypto/keys"
  10. )
  11. type data struct {
  12. info keys.Info
  13. salt []byte
  14. key []byte
  15. }
  16. type MemStore map[string]data
  17. // New creates an instance of file-based key storage with tight permissions
  18. func New() MemStore {
  19. return MemStore{}
  20. }
  21. // assert MemStore satisfies keys.Storage
  22. var _ keys.Storage = MemStore{}
  23. // Put adds the given key, returns an error if it another key
  24. // is already stored under this name
  25. func (s MemStore) Put(name string, salt, key []byte, info keys.Info) error {
  26. if _, ok := s[name]; ok {
  27. return errors.Errorf("Key named '%s' already exists", name)
  28. }
  29. s[name] = data{info, salt, key}
  30. return nil
  31. }
  32. // Get returns the key stored under the name, or returns an error if not present
  33. func (s MemStore) Get(name string) (salt, key []byte, info keys.Info, err error) {
  34. d, ok := s[name]
  35. if !ok {
  36. err = errors.Errorf("Key named '%s' doesn't exist", name)
  37. }
  38. return d.salt, d.key, d.info.Format(), err
  39. }
  40. // List returns the public info of all keys in the MemStore in unsorted order
  41. func (s MemStore) List() (keys.Infos, error) {
  42. res := make([]keys.Info, len(s))
  43. i := 0
  44. for _, d := range s {
  45. res[i] = d.info.Format()
  46. i++
  47. }
  48. return res, nil
  49. }
  50. // Delete removes the named key from the MemStore, raising an error if it
  51. // wasn't present yet.
  52. func (s MemStore) Delete(name string) error {
  53. _, ok := s[name]
  54. if !ok {
  55. return errors.Errorf("Key named '%s' doesn't exist", name)
  56. }
  57. delete(s, name)
  58. return nil
  59. }