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