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-keys"
  10. )
  11. type data struct {
  12. info keys.Info
  13. key []byte
  14. }
  15. type MemStore map[string]data
  16. // New creates an instance of file-based key storage with tight permissions
  17. func New() MemStore {
  18. return MemStore{}
  19. }
  20. // assertStorage just makes sure we implement the Storage interface
  21. func (s MemStore) assertStorage() keys.Storage {
  22. return s
  23. }
  24. // Put adds the given key, returns an error if it another key
  25. // is already stored under this name
  26. func (s MemStore) Put(name string, key []byte, info keys.Info) error {
  27. if _, ok := s[name]; ok {
  28. return errors.Errorf("Key named '%s' already exists", name)
  29. }
  30. s[name] = data{info, key}
  31. return nil
  32. }
  33. // Get returns the key stored under the name, or returns an error if not present
  34. func (s MemStore) Get(name string) ([]byte, keys.Info, error) {
  35. var err error
  36. d, ok := s[name]
  37. if !ok {
  38. err = errors.Errorf("Key named '%s' doesn't exist", name)
  39. }
  40. return d.key, d.info.Format(), err
  41. }
  42. // List returns the public info of all keys in the MemStore in unsorted order
  43. func (s MemStore) List() (keys.Infos, error) {
  44. res := make([]keys.Info, len(s))
  45. i := 0
  46. for _, d := range s {
  47. res[i] = d.info.Format()
  48. i++
  49. }
  50. return res, nil
  51. }
  52. // Delete removes the named key from the MemStore, raising an error if it
  53. // wasn't present yet.
  54. func (s MemStore) Delete(name string) error {
  55. _, ok := s[name]
  56. if !ok {
  57. return errors.Errorf("Key named '%s' doesn't exist", name)
  58. }
  59. delete(s, name)
  60. return nil
  61. }