-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmapstore.go
51 lines (41 loc) · 900 Bytes
/
mapstore.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package bitacoin
import (
"bytes"
"fmt"
)
type mapStore struct {
data map[string]*Block
last []byte
}
func (ms *mapStore) Load(hash []byte) (*Block, error) {
x := fmt.Sprintf("%x", hash)
if b, ok := ms.data[x]; ok {
return b, nil
}
return nil, fmt.Errorf("block is not in this store")
}
func (ms *mapStore) Append(b *Block) error {
if !bytes.Equal(ms.last, b.PrevHash) {
return fmt.Errorf("store is out of sync")
}
x := fmt.Sprintf("%x", b.Hash)
if _, ok := ms.data[x]; ok {
return fmt.Errorf("duplicate block")
}
ms.data[x] = b
ms.last = b.Hash
return nil
}
func (ms *mapStore) LastHash() ([]byte, error) {
if len(ms.last) == 0 {
return nil, ErrNotInitialized
}
return ms.last, nil
}
// NewMapStore is used to create an in memory and not persistant storage, useful
// for tests
func NewMapStore() Store {
return &mapStore{
data: make(map[string]*Block),
}
}