forked from celestiaorg/smt
-
Notifications
You must be signed in to change notification settings - Fork 3
/
smt_testutil.go
85 lines (75 loc) · 2.06 KB
/
smt_testutil.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package smt
import (
"bytes"
"errors"
)
// Wraps an SMT with value storage for use in tests.
// Uses a mapping to value preimages internally.
// Note: this doesn't delete from preimages, since there could be duplicate values.
type SMTWithStorage struct {
SparseMerkleTree
preimages MapStore
}
func (smt *SMTWithStorage) Update(key []byte, value []byte) error {
err := smt.SparseMerkleTree.Update(key, value)
if err != nil {
return err
}
valueHash := smt.base().digestValue(value)
err = smt.preimages.Set(valueHash, value)
if err != nil {
return err
}
return err
}
func (smt *SMTWithStorage) Delete(key []byte) error {
err := smt.SparseMerkleTree.Delete(key)
if err != nil {
return err
}
return nil
}
// Get gets the value of a key from the tree.
func (smt *SMTWithStorage) GetValue(key []byte) ([]byte, error) {
valueHash, err := smt.SparseMerkleTree.Get(key)
if err != nil {
return nil, err
}
value, err := smt.preimages.Get(valueHash)
if err != nil {
var invalidKeyError *InvalidKeyError
if errors.As(err, &invalidKeyError) {
// If key isn't found, return default value
value = defaultValue
} else {
// Otherwise percolate up any other error
return nil, err
}
}
return value, nil
}
// Has returns true if the value at the given key is non-default, false
// otherwise.
func (smt *SMTWithStorage) Has(key []byte) (bool, error) {
val, err := smt.GetValue(key)
return !bytes.Equal(defaultValue, val), err
}
// ProveCompact generates a compacted Merkle proof for a key against the current root.
func ProveCompact(key []byte, smt SparseMerkleTree) (SparseCompactMerkleProof, error) {
proof, err := smt.Prove(key)
if err != nil {
return SparseCompactMerkleProof{}, err
}
return CompactProof(proof, smt.base())
}
// dummyHasher is a dummy hasher for tests, where the digest of keys is equivalent to the preimage.
type dummyPathHasher struct {
size int
}
func (h dummyPathHasher) Path(key []byte) []byte {
if len(key) != h.size {
panic("len(key) must equal path size")
}
return key
}
func (h dummyPathHasher) PathSize() int { return h.size }