store_disk.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright © 2021 Ettore Di Giacinto <[email protected]>
  2. //
  3. // This program is free software; you can redistribute it and/or modify
  4. // it under the terms of the GNU General Public License as published by
  5. // the Free Software Foundation; either version 2 of the License, or
  6. // (at your option) any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License along
  14. // with this program; if not, see <http://www.gnu.org/licenses/>.
  15. package blockchain
  16. import (
  17. "encoding/json"
  18. "fmt"
  19. "strconv"
  20. "github.com/peterbourgon/diskv"
  21. )
  22. type DiskStore struct {
  23. chain *diskv.Diskv
  24. }
  25. func NewDiskStore(d *diskv.Diskv) *DiskStore {
  26. return &DiskStore{chain: d}
  27. }
  28. func (m *DiskStore) Add(b Block) {
  29. bb, _ := json.Marshal(b)
  30. m.chain.Write(fmt.Sprint(b.Index), bb)
  31. m.chain.Write("index", []byte(fmt.Sprint(b.Index)))
  32. }
  33. func (m *DiskStore) Len() int {
  34. count, err := m.chain.Read("index")
  35. if err != nil {
  36. return 0
  37. }
  38. c, _ := strconv.Atoi(string(count))
  39. return c
  40. }
  41. func (m *DiskStore) Last() Block {
  42. b := &Block{}
  43. count, err := m.chain.Read("index")
  44. if err != nil {
  45. return *b
  46. }
  47. dat, _ := m.chain.Read(string(count))
  48. json.Unmarshal(dat, b)
  49. return *b
  50. }