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.

68 lines
1.6 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. 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. // assert MemStore satisfies keys.Storage
  21. var _ keys.Storage = MemStore{}
  22. // Put adds the given key, returns an error if it another key
  23. // is already stored under this name
  24. func (s MemStore) Put(name string, key []byte, info keys.Info) error {
  25. if _, ok := s[name]; ok {
  26. return errors.Errorf("Key named '%s' already exists", name)
  27. }
  28. s[name] = data{info, key}
  29. return nil
  30. }
  31. // Get returns the key stored under the name, or returns an error if not present
  32. func (s MemStore) Get(name string) ([]byte, keys.Info, error) {
  33. var 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.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. }