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.

78 lines
1.8 KiB

  1. package certifiers
  2. import (
  3. "encoding/hex"
  4. "sort"
  5. certerr "github.com/tendermint/tendermint/certifiers/errors"
  6. )
  7. type memStoreProvider struct {
  8. // byHeight is always sorted by Height... need to support range search (nil, h]
  9. // btree would be more efficient for larger sets
  10. byHeight fullCommits
  11. byHash map[string]FullCommit
  12. }
  13. // fullCommits just exists to allow easy sorting
  14. type fullCommits []FullCommit
  15. func (s fullCommits) Len() int { return len(s) }
  16. func (s fullCommits) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  17. func (s fullCommits) Less(i, j int) bool {
  18. return s[i].Height() < s[j].Height()
  19. }
  20. func NewMemStoreProvider() Provider {
  21. return &memStoreProvider{
  22. byHeight: fullCommits{},
  23. byHash: map[string]FullCommit{},
  24. }
  25. }
  26. func (m *memStoreProvider) encodeHash(hash []byte) string {
  27. return hex.EncodeToString(hash)
  28. }
  29. func (m *memStoreProvider) StoreCommit(fc FullCommit) error {
  30. // make sure the fc is self-consistent before saving
  31. err := fc.ValidateBasic(fc.Commit.Header.ChainID)
  32. if err != nil {
  33. return err
  34. }
  35. // store the valid fc
  36. key := m.encodeHash(fc.ValidatorsHash())
  37. m.byHash[key] = fc
  38. m.byHeight = append(m.byHeight, fc)
  39. sort.Sort(m.byHeight)
  40. return nil
  41. }
  42. func (m *memStoreProvider) GetByHeight(h int) (FullCommit, error) {
  43. // search from highest to lowest
  44. for i := len(m.byHeight) - 1; i >= 0; i-- {
  45. fc := m.byHeight[i]
  46. if fc.Height() <= h {
  47. return fc, nil
  48. }
  49. }
  50. return FullCommit{}, certerr.ErrCommitNotFound()
  51. }
  52. func (m *memStoreProvider) GetByHash(hash []byte) (FullCommit, error) {
  53. var err error
  54. fc, ok := m.byHash[m.encodeHash(hash)]
  55. if !ok {
  56. err = certerr.ErrCommitNotFound()
  57. }
  58. return fc, err
  59. }
  60. func (m *memStoreProvider) LatestCommit() (FullCommit, error) {
  61. l := len(m.byHeight)
  62. if l == 0 {
  63. return FullCommit{}, certerr.ErrCommitNotFound()
  64. }
  65. return m.byHeight[l-1], nil
  66. }