/
create.go
104 lines (89 loc) · 2.67 KB
/
create.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package proofs
import (
"fmt"
"sort"
ics23 "github.com/confio/ics23/go"
sdkmaps "github.com/creatachain/creata-sdk/store/internal/maps"
)
// AugusteumSpec constrains the format from ics23-augusteum (crypto/merkle SimpleProof)
var AugusteumSpec = &ics23.ProofSpec{
LeafSpec: &ics23.LeafOp{
Prefix: []byte{0},
Hash: ics23.HashOp_SHA256,
PrehashValue: ics23.HashOp_SHA256,
Length: ics23.LengthOp_VAR_PROTO,
},
InnerSpec: &ics23.InnerSpec{
ChildOrder: []int32{0, 1},
MinPrefixLength: 1,
MaxPrefixLength: 1, // fixed prefix + one child
ChildSize: 32, // (no length byte)
Hash: ics23.HashOp_SHA256,
},
}
/*
CreateMembershipProof will produce a CommitmentProof that the given key (and queries value) exists in the iavl tree.
If the key doesn't exist in the tree, this will return an error.
*/
func CreateMembershipProof(data map[string][]byte, key []byte) (*ics23.CommitmentProof, error) {
exist, err := createExistenceProof(data, key)
if err != nil {
return nil, err
}
proof := &ics23.CommitmentProof{
Proof: &ics23.CommitmentProof_Exist{
Exist: exist,
},
}
return proof, nil
}
/*
CreateNonMembershipProof will produce a CommitmentProof that the given key doesn't exist in the iavl tree.
If the key exists in the tree, this will return an error.
*/
func CreateNonMembershipProof(data map[string][]byte, key []byte) (*ics23.CommitmentProof, error) {
// ensure this key is not in the store
if _, ok := data[string(key)]; ok {
return nil, fmt.Errorf("cannot create non-membership proof if key is in map")
}
keys := SortedKeys(data)
rightidx := sort.SearchStrings(keys, string(key))
var err error
nonexist := &ics23.NonExistenceProof{
Key: key,
}
// include left proof unless key is left of entire map
if rightidx >= 1 {
leftkey := keys[rightidx-1]
nonexist.Left, err = createExistenceProof(data, []byte(leftkey))
if err != nil {
return nil, err
}
}
// include right proof unless key is right of entire map
if rightidx < len(keys) {
rightkey := keys[rightidx]
nonexist.Right, err = createExistenceProof(data, []byte(rightkey))
if err != nil {
return nil, err
}
}
proof := &ics23.CommitmentProof{
Proof: &ics23.CommitmentProof_Nonexist{
Nonexist: nonexist,
},
}
return proof, nil
}
func createExistenceProof(data map[string][]byte, key []byte) (*ics23.ExistenceProof, error) {
value, ok := data[string(key)]
if !ok {
return nil, fmt.Errorf("cannot make existence proof if key is not in map")
}
_, ics23, _ := sdkmaps.ProofsFromMap(data)
proof := ics23[string(key)]
if proof == nil {
return nil, fmt.Errorf("returned no proof for key")
}
return ConvertExistenceProof(proof, key, value)
}