Browse Source

:ledger: Add memory and disk store

Ettore Di Giacinto 3 years ago
parent
commit
77f1930846
2 changed files with 69 additions and 0 deletions
  1. 48 0
      pkg/blockchain/store_disk.go
  2. 21 0
      pkg/blockchain/store_memory.go

+ 48 - 0
pkg/blockchain/store_disk.go

@@ -0,0 +1,48 @@
+package blockchain
+
+import (
+	"encoding/json"
+	"fmt"
+	"strconv"
+
+	"github.com/peterbourgon/diskv"
+)
+
+type disk struct {
+	chain *diskv.Diskv
+}
+
+func (m *disk) Add(b Block) {
+	bb, _ := json.Marshal(b)
+	m.chain.Write(fmt.Sprint(b.Index), bb)
+	m.chain.Write("index", []byte(fmt.Sprint(b.Index)))
+
+}
+
+func (m *disk) Reset() {
+	m.chain.EraseAll()
+}
+
+func (m *disk) Len() int {
+	count, err := m.chain.Read("index")
+	if err != nil {
+		return 0
+	}
+	c, _ := strconv.Atoi(string(count))
+	return c
+
+}
+
+func (m *disk) Last() Block {
+	b := &Block{}
+
+	count, err := m.chain.Read("index")
+	if err != nil {
+		return *b
+	}
+
+	dat, _ := m.chain.Read(string(count))
+	json.Unmarshal(dat, b)
+
+	return *b
+}

+ 21 - 0
pkg/blockchain/store_memory.go

@@ -0,0 +1,21 @@
+package blockchain
+
+type memory struct {
+	chain Blockchain
+}
+
+func (m *memory) Add(b Block) {
+	m.chain = append(m.chain, b)
+}
+
+func (m *memory) Reset() {
+	m.chain = []Block{}
+}
+
+func (m *memory) Len() int {
+	return len(m.chain)
+}
+
+func (m *memory) Last() Block {
+	return m.chain[len(m.chain)-1]
+}