go-merkletree-iden3/db/db.go
db/db.goRaw
1package db
2
3import (
4 "bytes"
5 "crypto/sha256"
6 "errors"
7)
8
9// ErrNotFound is used by the implementations of the interface db.Storage for
10// when a key is not found in the storage
11var ErrNotFound = errors.New("key not found")
12
13// Storage is the interface that defines the methods for the storage used in
14// the merkletree. Examples of the interface implementation can be found at
15// db/memory and db/leveldb directories.
16type Storage interface {
17 NewTx() (Tx, error)
18 WithPrefix(prefix []byte) Storage
19 Get([]byte) ([]byte, error)
20 List(int) ([]KV, error)
21 Close()
22 Info() string
23 Iterate(func([]byte, []byte) (bool, error)) error
24}
25
26// Tx is the interface that defines the methods for the db transaction used in
27// the merkletree storage. Examples of the interface implementation can be
28// found at db/memory and db/leveldb directories.
29type Tx interface {
30 Get([]byte) ([]byte, error)
31 Put(k, v []byte)
32 Add(Tx)
33 Commit() error
34 Close()
35}
36
37// KV contains a key (K) and a value (V)
38type KV struct {
39 K []byte
40 V []byte
41}
42
43// KvMap is a key-value map between a sha256 byte array hash, and a KV struct
44type KvMap map[[sha256.Size]byte]KV
45
46// Get retreives the value respective to a key from the KvMap
47func (m KvMap) Get(k []byte) ([]byte, bool) {
48 v, ok := m[sha256.Sum256(k)]
49 return v.V, ok
50}
51
52// Put stores a key and a value in the KvMap
53func (m KvMap) Put(k, v []byte) {
54 m[sha256.Sum256(k)] = KV{k, v}
55}
56
57// Concat concatenates arrays of bytes
58func Concat(vs ...[]byte) []byte {
59 var b bytes.Buffer
60 for _, v := range vs {
61 b.Write(v)
62 }
63 return b.Bytes()
64}
65
66// Clone clones a byte array into a new byte array
67func Clone(b0 []byte) []byte {
68 b1 := make([]byte, len(b0))
69 copy(b1, b0)
70 return b1
71}