arnaucube
arnaucube/go-merkletree-iden3Public Self-hosted repository
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 retreives the value for the given key
31	// looking first in the content of the Tx, and
32	// then into the content of the Storage
33	Get([]byte) ([]byte, error)
34	// Put sets the key & value into the Tx
35	Put(k, v []byte) error
36	// Add adds the given Tx into the Tx
37	Add(Tx) error
38	Commit() error
39	Close()
40}
41
42// KV contains a key (K) and a value (V)
43type KV struct {
44	K []byte
45	V []byte
46}
47
48// KvMap is a key-value map between a sha256 byte array hash, and a KV struct
49type KvMap map[[sha256.Size]byte]KV
50
51// Get retreives the value respective to a key from the KvMap
52func (m KvMap) Get(k []byte) ([]byte, bool) {
53	v, ok := m[sha256.Sum256(k)]
54	return v.V, ok
55}
56
57// Put stores a key and a value in the KvMap
58func (m KvMap) Put(k, v []byte) {
59	m[sha256.Sum256(k)] = KV{k, v}
60}
61
62// Concat concatenates arrays of bytes
63func Concat(vs ...[]byte) []byte {
64	var b bytes.Buffer
65	for _, v := range vs {
66		b.Write(v)
67	}
68	return b.Bytes()
69}
70
71// Clone clones a byte array into a new byte array
72func Clone(b0 []byte) []byte {
73	b1 := make([]byte, len(b0))
74	copy(b1, b0)
75	return b1
76}